我在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
?
答案 0 :(得分:2)
我已经弄明白了问题所在。如果我们将“标签”列设置为索引,则会自动标记y轴。
df = pandas.DataFrame(data, columns=['Label', 'Col1', 'Col2'])
df.index = df['Label']
df.plot(kind='barh')
plt.show()
答案 1 :(得分:1)
不需要修改DataFrame。创建绘图后,您可以使用plt.yticks
设置标签:
plt.yticks(range(3),df['Label'])