如何在使用 pandas 图创建的图上添加共享的x标签和y标签? [英] How to add a shared x-label and y-label to a plot created with pandas' plot?

查看:479
本文介绍了如何在使用 pandas 图创建的图上添加共享的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=20)

现在如何将x标签和y标签添加到结果图中? 此处,仅针对单个图进行说明.因此,如果我想为特定子图添加标签,我可以这样做:

How would one now add the x- and y-labels to the resulting plot? Here it is explained for a single plot. So if I wanted to add labels to a particular subplot I could do:

ax[1][0].set_xlabel('my_general_xlabel')
ax[0][0].set_ylabel('my_general_ylabel')
plt.show()

给出:

一个人如何添加标签,使它们居中,而不只是引用一个行/列?

How would one add the labels so that they are centred and do not just refer to a one row/column?

推荐答案

X和y标签绑定到matplotlib中的轴.因此,使用xlabelylabel命令来标记多个子图几乎没有意义.

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.

但是,可以创建一个简单的文本并将其放置在所需的位置. fig.text(x,y, text)在图形坐标中的坐标xy处放置一些文本,即图形的左下角具有坐标(0,0)右上角为(1,1).

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).

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.

这篇关于如何在使用 pandas 图创建的图上添加共享的x标签和y标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆