【问题标题】:Can I add y-axis labels on a horizontal barchart using pandas?我可以使用 pandas 在水平条形图上添加 y 轴标签吗?
【发布时间】:2015-11-11 21:01:37
【问题描述】:

我在 matplotlib 周围使用pandas 包装器来创建水平条形图,并希望在 y 轴上添加标签。

遗憾的是,它似乎不像我们在饼图中添加 labels=df['Labels'] 参数那么简单。

import pandas
import matplotlib.pyplot as plt

data = [['A', 1, 2], ['B', 2, 3], ['C', 3, 4]]
df = pandas.DataFrame(data, columns=['Label', 'Col1', 'Col2'])
df.plot(kind='barh')
plt.show()

这是否可能仅在 pandas 中实现,还是我将不得不搬到 matplotlib

【问题讨论】:

    标签: python pandas axis-labels


    【解决方案1】:

    不需要修改 DataFrame。创建绘图后,您可以使用plt.yticks 设置标签:

    plt.yticks(range(3),df['Label'])
    

    【讨论】:

      【解决方案2】:

      我已经弄清楚了问题所在。如果我们将 'Label' 列设置为索引,则 y 轴会自动标记。

      df = pandas.DataFrame(data, columns=['Label', 'Col1', 'Col2'])
      df.index = df['Label']
      df.plot(kind='barh')
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-22
        • 1970-01-01
        • 2013-06-02
        • 2014-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-22
        相关资源
        最近更新 更多