为什么pyplot.plot()创建一个宽度为1,高度为1的附加Rectangle? [英] Why does pyplot.plot() create an additional Rectangle with width=1, height=1?

查看:94
本文介绍了为什么pyplot.plot()创建一个宽度为1,高度为1的附加Rectangle?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a simple bar plot from a DataFrame. (The plot method on Series and DataFrame is just a simple wrapper around 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')

这是生成的情节

This is the generated plot

现在,我要访问各个栏.我注意到的是,还有一个宽度(宽度)= 1,高度(高度)= 1

Now I want to access the individual bars. And what I've noticed is that there is an additional bar (Rectangle) with width=1, height=1

rects = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)]
for r in rects:
   print(r)

输出:

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)

我希望这里只有三个矩形.第四种目的是什么?

I would expect only three rectangles here. What is the purpose of the fourth?

推荐答案

第四个矩形是Axis子图的边界框.
这是Pyplot处理边界框的方式的一种人工产物,并非特定于Pandas.例如,使用常规Pyplot进行绘图:

The fourth Rectangle is the bounding box for the Axis subplot.
This is an artifact of the way Pyplot handles bounding boxes, it's not specific to Pandas. For example, plotting with regular 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)

仍然会产生四个矩形:

Rectangle(-0.4,0;0.8x3.42635e+06)
Rectangle(0.6,0;0.8x1.26039e+06)
Rectangle(1.6,0;0.8x1.73912e+06)
Rectangle(0,0;1x1)

Pyplot紧密布局文档中有一行,它引用了这个额外的矩形(和也是为什么它的坐标是(0,0),(1,1).它指的是rect参数:

There's a line in the Pyplot tight layout docs which refers to this extra Rectangle (and also why its coordinates are (0,0),(1,1). It refers to a rect parameter:

...,它指定子图将适合的边界框.坐标必须为归一化的图形坐标,默认值为(0,0,1,1).

...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文档中可能有一个更正式的部分,它更全面地描述了该体系结构,但是我发现这些文档难以浏览,这是我能想到的最好的结果.

There's probably a more official section of the Matplotlib documentation that describes this architecture more thoroughly, but I find those docs difficult to navigate, this is the best I could come up with.

这篇关于为什么pyplot.plot()创建一个宽度为1,高度为1的附加Rectangle?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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