更多pandas.DataFrame.plot(kind="bar")的绘图选项

1 投票
1 回答
3675 浏览
提问于 2025-04-18 07:14

pandas.DataFrame.plot(kind='bar')这个方法很方便,因为它可以根据数据框的行和列来绘制分组的、颜色合适的柱状图。例如:

timeDf.plot(kind='bar', legend=False)

这样会生成:

enter image description here

对应的数据框如下:

enter image description here

但是,如果我想让图表有,比如说:

  • 对数y轴
  • y轴和x轴的标签

这个方法似乎没有这些选项?是说它的自定义支持很有限,还是我漏掉了什么?

我不太想在matplotlib中重新构建这个绘图功能,因为我觉得那会很麻烦。

1 个回答

3

这里有两个方法,分别是 set_scaleset_xticklabels,可以用来设置图表的刻度。

df=pd.DataFrame(np.random.random((6,6)))
ax=df.plot(kind='bar')
ax.yaxis.set_scale('log')
ax.set_xticklabels(['a','b','c','d','e','f'])

这里插入图片描述

如果你想让刻度均匀分布,可以这样做:

ax.set_yscale("log", nonposy='clip') #nonposy is required, otherwise the bar disappears.
ax.set_ylim((0.1, 100)) #remember to rest the limit.

这里插入图片描述

matplotlib 1.3 版本开始,set_scale 这个方法已经不再推荐使用,取而代之的是 _set_scale

撰写回答