pandas 如何将共享的 x 标签和 y 标签添加到使用熊猫绘图创建的绘图中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42372509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a shared x-label and y-label to a plot created with pandas' plot?
提问by Cleb
One can create subplots easily from a dataframe using pandas:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20)
How would one now add the x- and y-labels to the resulting plot? Hereit is explained for a single plot. So if I wanted to add labels to a particular subplot I could do:
现在如何将 x 和 y 标签添加到结果图中?此处针对单个图进行解释。因此,如果我想为特定子图添加标签,我可以这样做:
ax[1][0].set_xlabel('my_general_xlabel')
ax[0][0].set_ylabel('my_general_ylabel')
plt.show()
That gives:
这给出了:
How would one add the labels so that they are centred and do not just refer to a one row/column?
如何添加标签,使它们居中,而不仅仅是指一行/列?
回答by ImportanceOfBeingErnest
X and y labels are bound to an axes in matplotlib. So it makes little sense to use xlabel
or ylabel
commands for the purpose of labeling several subplots.
X 和 y 标签绑定到 matplotlib 中的轴。因此,使用xlabel
或ylabel
命令来标记多个子图是没有意义的。
What is possible though, is to create a simple text and place it at the desired position. fig.text(x,y, text)
places some text at coordinates x
and y
in figure coordinates, i.e. the lower left corner of the figure has coordinates (0,0)
the upper right one (1,1)
.
但是,可能的是创建一个简单的文本并将其放置在所需的位置。fig.text(x,y, text)
地方一些文字的坐标x
和y
图坐标,也就是图的左下角有坐标(0,0)
右上方的(1,1)
。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
axes = df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True)
fig=axes[0,0].figure
fig.text(0.5,0.04, "Some very long and even longer xlabel", ha="center", va="center")
fig.text(0.05,0.5, "Some quite extensive ylabel", ha="center", va="center", rotation=90)
plt.show()
The drawback of this solution is that the coordinates of where to place the text need to be set manually and may depend on the figure size.
这种解决方案的缺点是需要手动设置放置文本位置的坐标,并且可能取决于图形大小。
回答by SparkAndShine
Another solution: create a big subplot and then set the common labels. Here is what I got.
另一种解决方案:创建一个大的子图,然后设置公共标签。这是我得到的。
The source code is below.
源代码如下。
import pandas as pd
import matplotlib.pyplot as plt
fig = plt.figure()
axarr = fig.add_subplot(221)
df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
axes = df.plot(kind="bar", ax=axarr, subplots=True, layout=(2, 2), sharey=True, sharex=True, rot=0, fontsize=20)
# Create a big subplot
ax = fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
ax.set_xlabel('my_general_xlabel', labelpad=10) # Use argument `labelpad` to move label downwards.
ax.set_ylabel('my_general_ylabel', labelpad=20)
plt.show()
回答by Pablo Reyes
This will create an invisible 111 axis where you can set the general x and y labels:
这将创建一个不可见的 111 轴,您可以在其中设置常规 x 和 y 标签:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1],
'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]},
index=list('abcd'))
ax = df.plot(kind="bar", subplots=True, layout=(2, 2), sharey=True,
sharex=True, rot=0, fontsize=12)
fig = ax[0][0].get_figure() # getting the figure
ax0 = fig.add_subplot(111, frame_on=False) # creating a single axes
ax0.set_xticks([])
ax0.set_yticks([])
ax0.set_xlabel('my_general_xlabel', labelpad=25)
ax0.set_ylabel('my_general_ylabel', labelpad=45)
# Part of a follow up question: Modifying the fontsize of the titles:
for i,axi in np.ndenumerate(ax):
axi.set_title(axi.get_title(),{'size' : 16})