pandas 如何并排绘制2个直方图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45069828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:59:19  来源:igfitidea点击:

how to plot 2 histograms side by side?

pandasmatplotlibhistogram

提问by Mark Ginsburg

I have 2 dataframes. I want to plot a histogram based on a column 'rate' for each, side by side. How to do it?

我有 2 个数据框。我想并排绘制基于列“速率”的直方图。怎么做?

I tried this:

我试过这个:

import matplotlib.pyplot as plt
plt.subplot(1,2,1)

dflux.hist('rate' , bins=100) 
plt.subplot(1,2,2) 
dflux2.hist('rate' , bins=100) 
plt.tight_layout() 
plt.show() 

It did not have the desired effect. It showed two blank charts then one populated chart.

它没有达到预期的效果。它显示了两个空白图表,然后是一个填充图表。

回答by piRSquared

Use subplotsto define a figure with two axes. Then specify the axis to plot to within histusing the axparameter.

使用subplots定义有两个轴的身影。然后hist使用ax参数指定要绘制到的轴。

fig, axes = plt.subplots(1, 2)

dflux.hist('rate', bins=100, ax=axes[0])
dflux2.hist('rate', bins=100, ax=axes[1])

Demo

演示

dflux = pd.DataFrame(dict(rate=np.random.randn(10000)))
dflux2 = pd.DataFrame(dict(rate=np.random.randn(10000)))

fig, axes = plt.subplots(1, 2)

dflux.hist('rate', bins=100, ax=axes[0])
dflux2.hist('rate', bins=100, ax=axes[1])

enter image description here

在此处输入图片说明