【问题标题】:Add labels and title to a plot made using pandas为使用 pandas 制作的绘图添加标签和标题
【发布时间】:2020-12-18 09:11:42
【问题描述】:

我使用以下代码制作了一个简单的直方图:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
pd.Series(a).value_counts().plot('bar')

虽然这是绘制频率直方图的简洁方法,但我不确定如何自定义绘图,即:

  1. 添加标题
  2. 添加轴标签
  3. 在 x 轴上对值进行排序

【问题讨论】:

  • 查看pandas.DataFrame.plot 的 API,快速浏览一下,我看到了 1,2 和 3 的正确参数
  • ax = pd.Series(a).value_counts().plot(kind='bar', title='I should read the docs', xlabel='xlabel', ylabel='ylabel')

标签: python pandas plot


【解决方案1】:

Series.plot(或DataFrame.plot)返回一个matplotlib axis 对象,它公开了几个方法。例如:

a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
ax = pd.Series(a).value_counts().sort_index().plot('bar')
ax.set_title("my title")
ax.set_xlabel("my x-label")
ax.set_ylabel("my y-label")

n.b.:pandas 在这里使用 matplotlib 作为依赖项,并且公开了 matplotlib 对象和 api。您可以通过import matplotlib.pyplot as plt; ax = plt.subplots(1,1,1) 获得相同的结果。如果您一次创建多个绘图,您会发现ax.<method> 比模块级别plt.title('my title') 方便得多,因为它定义了您想要更改的哪个绘图标题和您可以利用 ax 对象上的自动完成功能。

【讨论】:

    【解决方案2】:

    您可以使用matplotlib 对其进行自定义。你可以看到我使用.sort_index() 对xlabels 进行排序。

    import matplotlib.pyplot as plt
    
    a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
    pd.Series(a).value_counts().sort_index().plot(kind='bar')
    plt.title('My Title')
    plt.xlabel('My X Label')
    
    

    【讨论】:

      【解决方案3】:

      如 cmets 中所述,您现在只需使用 titlexlabelylabel 参数(并使用 kind 参数作为绘图类型):

      a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']    
      pd.Series(a).value_counts().plot(kind='bar', title="Your Title", xlabel="X Axis", ylabel="Y Axis")
      

      请参阅Pandas plot() docs 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2022-12-12
        • 1970-01-01
        相关资源
        最近更新 更多