使用“by”参数为pandas直方图添加标题

0 投票
1 回答
2254 浏览
提问于 2025-04-17 16:41

我该如何给使用pandas的hist函数在Series上创建的直方图添加标题,特别是在使用“by”参数的情况下呢?

如果只是简单的直方图,那就没问题了。比如,下面的代码就能正常工作:

In [115]: runELMLearning.utime.hist()
Out[115]: <matplotlib.axes.AxesSubplot at 0x20aaa590>

In [116]: plt.title("fooo")
Out[116]: <matplotlib.text.Text at 0x228b8550>

但是,当使用“by”这个参数时,就不行了:

In [117]: runELMLearning.utime.hist(by=runELMLearning.state)
Out[117]: 
array([[Axes(0.1,0.763636;0.222222x0.136364),
        Axes(0.388889,0.763636;0.222222x0.136364),
        Axes(0.677778,0.763636;0.222222x0.136364)],
       [Axes(0.1,0.559091;0.222222x0.136364),
        Axes(0.388889,0.559091;0.222222x0.136364),
        Axes(0.677778,0.559091;0.222222x0.136364)],
       [Axes(0.1,0.354545;0.222222x0.136364),
        Axes(0.388889,0.354545;0.222222x0.136364),
        Axes(0.677778,0.354545;0.222222x0.136364)],
       [Axes(0.1,0.15;0.222222x0.136364),
        Axes(0.388889,0.15;0.222222x0.136364),
        Axes(0.677778,0.15;0.222222x0.136364)]], dtype=object)

In [118]: plt.title("fooo")
Out[118]: <matplotlib.text.Text at 0x13612b10>

虽然没有报错,但标题却被悄悄忽略了。

我还发现一个奇怪的现象,就是如果我先创建一个图形,然后再使用hist函数,在使用“by”参数的情况下,之前创建的图形会被忽略,hist函数会创建一个新的图形,而我找不到matplotlib的当前坐标轴(gca)。对于简单的直方图来说,这个问题就不存在。

1 个回答

0

好的,我自己找到了这个问题的解决办法:我需要使用pyplot中的suptitle来给整个图形加标题,而不是给每个子图单独加标题,这种情况发生在有多个直方图的子图中。

http://matplotlib.1069221.n5.nabble.com/title-when-using-subplot-td22151.html

撰写回答