Skip to main content
 首页 » 编程设计

python之Matplotlib 两个图表上的相同直方图

2025年05月04日10Terrylee

我试图在 Matplotlib 中的两个图表上创建相同的直方图,但出于某种原因,这段代码无法正常工作。我在其中一个聊天中获得了直方图,但在另一个聊天中却没有。

fig,(ax1,ax2) = plt.subplots(1,2) 
ax1 = diamonds['price'].hist(bins = 50, color = 'black') 
ax2 = diamonds['price'].hist(bins = 50, color = 'black') 

如有任何建议,我们将不胜感激。

谢谢

请您参考如下方法:

从您的代码片段中不是特别清楚 diamonds 是什么,但让我们想象它是一个 pandas DataFrame。

您需要将轴句柄传递给每个直方图。

diamonds['price'].hist(bins=50, color='black', ax=ax1) 
diamonds['price'].hist(bins=50, color='black', ax=ax2) 

Here's pandas.DataFrame.hist 方法的文档页面。