Skip to main content
 首页 » 编程设计

python之如何使用 pandas 中的 DataFrame.hist(by=) 在特定轴上绘制

2025年05月04日8zhenyulu

我正在尝试在同一图中绘制多个直方图组。每个组包含两个条件,因此我使用 pandas 直方图选项中的 'by=' 参数。但是,这并不像我预期的那样有效, Pandas 创建了一个新图形而不是在我经过的轴上绘制。我也试过了四轴,但还是不行。示例代码:

import pandas as pd 
df = pd.DataFrame({'color': ['blue','blue','yellow','blue','yellow'], 'area': [2,2,3,4,4]}) 
fig, (ax1, ax2) = plt.subplots(1,2) 
df.area.hist(by=df.color, ax=ax1) 

我使用的是 pandas 0.12.0、matplotlib 1.3.0 和 python 2.7.5。欢迎提出在同一个子图网格中组合/拼接多个“hist(by=)-plots”的任何建议。

更新:

也许这更准确地描述了我想要实现的目标。

import pandas as pd 
df = pd.DataFrame({'color': ['blue','blue','yellow','blue','yellow'], 'area': [2,2,3,4,4]}) 
#fig, (ax1, ax2) = plt.subplots(1,2) 
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2) 
ax3.plot([[2,2], [3,6]]) 
ax4.plot([[3,6], [2,2]]) 
df.area.hist(by=df.color, ax=ax1) 

理想情况下,在我的示例中,pandas 直方图是 1,2,然后应该将 ax1 分成两个子图。或者,它可以绘制成 ax1 和 ax2,然后用户可以确保可用的空子图数量正确。

请您参考如下方法:

自 GH7736 起已修复合并到 pandas 0.15.0

将多个绘图传递到现有图形中的正确方法是首先创建所有需要的轴,然后将它们全部传递给 pandas 绘图命令。

import pandas as pd 
import matplotlib.pyplot as plt 
 
df = pd.DataFrame({'color': ['blue','blue','yellow','blue','yellow'], 'area': [2,2,3,4,4]}) 
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2) 
#Hide upper left corner plot and create two new subplots 
ax1.axis('off') 
ax = fig.add_subplot(2,4,1) 
ax0 = fig.add_subplot(2,4,2) 
#Plot 
ax3.plot([[2,2], [3,6]]) 
ax4.plot([[3,6], [2,2]]) 
df.area.hist(by=df.color, ax=(ax,ax0)) #Pass both new subplots 

您可以使用 GridSpec 更优雅地创建子图