【问题标题】:Matplotlib Line Plot not indicating LabelsMatplotlib 线图未指示标签
【发布时间】:2020-09-25 13:34:11
【问题描述】:

我有以下数据集,我想从中获取线图。情节是正确的,但尽管我在代码中提供了标签名称,但标签丢失了。请为我提供一种包含标签的方法。此外,如果我尝试在代码中包含 xlabel 和 ylabel,它会给我一个错误 AttributeError: 'Line2D' object has no property 'xlabel'

数据帧资源

UserId     |   date                 |-7|-6|-5|-4|-3|-2|-1|0 |1 |2 |3 |4 |5 |6 |7
     1      2009-10-17 17:38:32.590 |0 |0 |0 |0 |0 |0 |1 |0 |1 |0 |0 |0 |0 |0 |0  
     2      2009-10-19 00:37:23.067 |0 |0 |0 |0 |0 |1 |1 |0 |1 |0 |0 |0 |0 |0 |0    
     3      2009-10-20 08:37:14.143 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0 
     4      2009-10-21 18:07:51.247 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0 
     5      2009-10-22 21:25:24.483 |0 |0 |0 |0 |0 |0 |1 |0 |0 |0 |0 |0 |0 |0 |0

代码

badges = ["A", "B", "C"]

for badge in badges:
  res.iloc[:,2:].mean().plot(kind='line', label = badge)

输出

这是从此代码获得的输出。我希望所有三条线的标签都出现在图中。除此之外,我想在轴上添加 xlabel = "Week" 和 ylabel = "Mean Posts"。

【问题讨论】:

    标签: python dataframe matplotlib seaborn


    【解决方案1】:

    xlabel 或 ylabel 参数仅在 pandas 版本 1.1.0 中可用。或以上。 参考文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html#pandas.DataFrame.plot

    您收到 AttributeError: 'Line2D' object has no property 'xlabel' 的原因是您可能使用了较低版本的 pandas。

    您可以通过运行以下命令检查 pandas 版本

    import pandas as pd
    print(pd.__version__)
    

    现在要放置 x_label / y_label,您可以执行以下操作:

    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    for badge in badges:
      res.iloc[:,2:].mean().plot(kind='line', label = badge, ax=ax)
    ax.set_ylabel('y') 
    ax.set_xlabel('x')
    ax.legend()
    plt.show()   
    

    【讨论】:

      【解决方案2】:

      显示图例和轴标签所需的基本函数是plt.legendplt.xlabelplt.ylabel。请参阅下面的独立示例。如果不查看代码的所有相关部分,很难更具体。

      import matplotlib.pyplot as plt
      
      x = [1, 2, 3]
      y1 = [4, 5, 6]
      y2 = [7, 8, 9]
      
      plt.plot(x, y1, "b", label="y1")
      plt.plot(x, y2, "r", label="y2")
      plt.legend()
      plt.xlabel("x")
      plt.ylabel("y")
      plt.savefig("temp")
      

      【讨论】:

        【解决方案3】:

        您可以将plt.legend()plt.xlabelplt.ylabelplt.xticks 等所有参数保留在for 循环之外。

        试试这个:

        import pandas as pd
        import matplotlib.pyplot as plt
        import seaborn as sns
        
        sns.set_style('darkgrid')
        badges = ["A", "B", "C"]
        
        for badge in badges:
          res.iloc[:,2:].mean().plot(kind='line', label = badge)
        
        plt.ylabel('y',size=20,weight='bold') 
        plt.xlabel('x',size=20,weight='bold')
        plt.legend(frameon=False, prop={'size':15})
        plt.show()      
        

        此外,如果您希望每个 badge 有 3 个单独的图,则将部分从 plt.ylabel() 移动到循环内的 plt.show()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-05
          • 1970-01-01
          • 2023-03-23
          • 2015-01-25
          • 2022-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多