我正在从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