Python 为分组列创建直方图

Python 为分组列创建直方图,python,pandas,matplotlib,plot,histogram,Python,Pandas,Matplotlib,Plot,Histogram,我对Python绝对是新手。如何创建一行三列的绘图,在每列中绘制直方图?数据来自此数据帧: import pandas as pd import matplotlib as plt d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}

我对Python绝对是新手。如何创建一行三列的绘图,在每列中绘制直方图?数据来自此数据帧:

 import pandas as pd
import matplotlib as plt
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)
在DataFrame中,我们有三个组(A、B、C),但我可以有N个组,我仍然希望有一个带有一行的图,每个列是每个组的直方图。
谢谢

我想这就是您搜索的代码:

import pandas as pd
import matplotlib.pyplot as plt
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)

keys = sorted(df['col1'].unique())

vals = []
for k in keys:
    vals.append(sum(df.loc[df['col1'] == k]['col2']))

print(vals)

plt.bar(keys, vals)
plt.show()
这是您在本例中得到的结果:


问我你是否需要一个解释(或者只是谷歌一下)☻).

您可以旋转数据帧并链接plot命令以生成图形

import pandas as pd
import matplotlib.pyplot as plt

d = {'Category': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'Values': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 2 ]}
df = pd.DataFrame(d)

df.pivot(columns='Category', values='Values').plot(kind='hist', subplots=True, rwidth=0.9, align='mid')

编辑:您可以使用下面的代码在一行中绘制所有子绘图。但是,对于三个以上的类别,绘图开始看起来非常拥挤

df2 = df.pivot(columns='Category', values='Values')
color = ['blue', 'green', 'red']
idx = np.arange(1, 4)
plt.subplots(1, 3)
for i, col, colour in zip(idx, df2.columns, color):
    plt.subplot(1, 3, i)
    df2.loc[:, col].plot.hist(label=col, color=colour, range=(df['Values'].min(), df['Values'].max()), bins=11)
    plt.yticks(np.arange(3))
    plt.legend()

您可以创建一行子批次,并用直方图填充每个子批次:

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.ticker import FormatStrFormatter

#define toy dataset
d = {'col1': ['A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'], 
     'col2': [3, 4, 3, 4, 6, 7, 8, 9, 3, 2, 3, 4, 5, 3, 4, 1, 2, 6 ]}
df = pd.DataFrame(data=d)

#number of bins for histogram
binnr = 4
#group data in dataframe
g = df.groupby("col1")
#create subplots according to unique elements in col1, same x and y scale for better comparison
fig, axes = plt.subplots(1, len(g), sharex = True, sharey = True)
#just in case you will extend it to a 2D array later
axes = axes.flatten()

#minimum and maximum value of bins to have comparable axes for all histograms
binmin = df["col2"].min()
binmax = df["col2"].max()

#fill each subplot with histogram
for i, (cat, group) in enumerate(g): 
    axes[i].set_title("graph {} showing {}".format(i, cat))
    _counts, binlimits, _patches = axes[i].hist(group["col2"], bins = binnr, range = (binmin, binmax))

#move ticks to label the bin borders
axes[0].set_xticks(binlimits)
#prevent excessively long tick labels
axes[0].xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))
plt.tight_layout()
plt.show()
样本输出:

直方图是什么意思?col1中“B”的计数,或对应于“B”的col2值的总和?它是hist()从matplotlib。你的问题可以有不同的解释。我知道不需要一行子图,直方图应该在同一个图中。这是正确的吗?好的,对不起。我希望每组有一个图,每个图应该相邻,如:a B C。下面的示例非常完美,但没有图在彼此下方,我需要相邻的图。谢谢。这就是我要找的。有没有办法让图在同一行中?与其让它们一个在另一行的下方,不如让它们一个接一个,比如:a B CI编辑了我的答案,以创建具有所需格式的图。我的观点是,这不值得努力。Vertica如果您有三个以上的类别,lly-stacked子图工作得更好。谢谢!我得到以下错误:AttributeError:module'matplotlib'没有属性'subplot',我想这是因为我没有将matplotlib.pyplot作为plt导入,而是将import matplotlib作为plt导入。您能用更改后的导入命令尝试一下吗?我对例如,上面KRKirov的示例代码,但不是让绘图在彼此下方,而是让绘图彼此相邻,谢谢。