为什么pyplot.plot绘图()创建一个宽度为1,高度为1的额外矩形?

2024-04-20 09:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从一个数据帧创建一个简单的条形图。(Series和DataFrame上的plot方法只是一个简单的包装pyplot.plot绘图)在

import pandas as pd
import matplotlib as mpl

df = pd.DataFrame({'City': ['Berlin', 'Munich', 'Hamburg'],
               'Population': [3426354, 1260391, 1739117]})
df = df.set_index('City')

ax = df.plot(kind='bar')

这是生成的绘图
enter image description here

现在我想进入各个酒吧。我注意到有一个额外的条(矩形),宽度=1,高度=1

^{pr2}$

输出:

Rectangle(xy=(-0.25, 0), width=0.5, height=3.42635e+06, angle=0)
Rectangle(xy=(0.75, 0), width=0.5, height=1.26039e+06, angle=0)
Rectangle(xy=(1.75, 0), width=0.5, height=1.73912e+06, angle=0)
Rectangle(xy=(0, 0), width=1, height=1, angle=0)

我想这里只有三个矩形。第四个目标是什么?在


Tags: 数据import绘图citydataframedfplotas
2条回答

第四个矩形是轴子图的边界框。
这是Pyplot处理边界框的方式的一个人工制品,它不是熊猫特有的。例如,使用常规Pyplot打印:

f, ax = plt.subplots()
ax.bar(range(3), df.Population.values)
rects = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)]
for r in rects:
    print(r)

仍然会生成四个矩形:

^{pr2}$

Pyplot tight layout docs中有一条线引用了这个额外的矩形(以及它的坐标是(0,0),(1,1))的原因。引用rect参数:

...which specifies the bounding box that the subplots will be fit inside. The coordinates must be in normalized figure coordinates and the default is (0, 0, 1, 1).

Matplotlib文档中可能有更官方的部分更详细地描述了这种架构,但是我发现这些文档很难导航,这是我能想到的最好的。在

你不想为了得到感兴趣的东西而和斧子的孩子们捣乱。如果轴上只有条形图,ax.patches会给出轴上的矩形。在

关于酒吧的标签,连锁商品可能不是最好的选择。它主张手动计算标签的距离,这并不是真正有用的。相反,您只需使用参数textcoords="offset points"到{},将注释偏移一些点。在

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'City': ['Berlin', 'Munich', 'Hamburg'],
               'Population': [3426354, 1260391, 1739117]})
df = df.set_index('City')

ax = df.plot(kind='bar')


def autolabel(rects, ax):
    for rect in rects:
        x = rect.get_x() + rect.get_width()/2.
        y = rect.get_height()
        ax.annotate("{}".format(y), (x,y), xytext=(0,5), textcoords="offset points",
                    ha='center', va='bottom')

autolabel(ax.patches,ax)

ax.margins(y=0.1)
plt.show()

enter image description here

最后请注意,使用绘图中的形状来创建注释可能仍然不是最佳选择。为什么不使用数据本身呢?在

^{pr2}$

这将生成与上面相同的图。在

相关问题 更多 >