python pyplot 宽高等比_python-为什么pyplot.plot()创建一个宽度为= 1,高度为= 1的附加Rectangle?...

我正在从DataFrame创建一个简单的条形图. (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')

这是生成的图

现在,我要访问各个栏.我注意到的是,还有一个附加的条(矩形),其宽度= 1,高度= 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)

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

解决方法:

第四个Rectangle是Axis子图的边界框.

这是Pyplot处理边界框的方式的一种人工产物,并非特定于Pandas.例如,使用常规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 tight layout docs中有一行引用此额外的Rectangle(以及为什么其坐标为(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文档中可能有一个更正式的部分,它更全面地描述了此体系结构,但是我发现这些文档难以浏览,这是我能想到的最好的文档.

标签:pandas,matplotlib,plot,python

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值