Overlaying multiple histograms using pandas(使用 pandas 叠加多个直方图)
问题描述
我有两个或三个具有相同标题的 csv 文件,我想绘制每一列的直方图,并在同一图上相互重叠.
I have two or three csv files with the same header and would like to draw the histograms for each column overlaying one another on the same plot.
以下代码为我提供了两个单独的图形,每个图形都包含每个文件的所有直方图.是否有一种紧凑的方法可以使用 pandas/matplot lib 将它们绘制在同一个图形上?我想象一些接近这个但使用数据帧的东西.
The following code gives me two separate figures, each containing all histograms for each of the files. Is there a compact way to go about plotting them together on the same figure using pandas/matplot lib? I imagine something close to this but using dataframes.
代码:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('input1.csv')
df2 = pd.read_csv('input2.csv')
df.hist(bins=20)
df2.hist(bins=20)
plt.show()
推荐答案
In [18]: from pandas import DataFrame
In [19]: from numpy.random import randn
In [20]: df = DataFrame(randn(10, 2))
In [21]: df2 = DataFrame(randn(10, 2))
In [22]: axs = df.hist()
In [23]: for ax, (colname, values) in zip(axs.flat, df2.iteritems()):
....: values.hist(ax=ax, bins=10)
....:
In [24]: draw()
给出
这篇关于使用 pandas 叠加多个直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!