我有一个熊猫数据框,其中有一个列age
,我想将其显示为直方图。
我可以轻松使用以下方法:
df.age.hist(bins=<bin_num>)
要么
df.hist('age', bins=<bin_num>)
但是,在同一张图纸上,我想显示另一列中的一些信息,例如该bin中平均height
个数据点。
这可能是线图(或其他某种类型的图)。
我还希望能够轻松地将函数从平均值更改为最大值/最小值/平均值/等。
主要问题是我真的不知道hist
在每个容器中放置哪些值。
答案 0 :(得分:0)
Matplotlib中的Hist图形返回BarContainer,其中包含Barplot的所有属性。您可以遍历每个条形,并获取每个条形的“ x”值和高度。
df_age = pd.DataFrame({'AGE': np.random.randint(1,100,200) })
fig,ax = plt.subplots()
plt.hist(df_age['AGE'])
bar_height = []
bar_x = []
bar_x_lst = []
bar_y_lst = []
for bar in ax.patches:
bar_x.append(bar.get_x())
bar_height.append(bar.get_height())
for i,val in enumerate(bar_x):
if i==0:
bar_x_lst.append(val)
continue
bar_x_lst+=[val-0.1,val]
for i,val in enumerate(bar_height):
if i ==len(bar_height)-1:
bar_y_lst.append(val)
continue
bar_y_lst += [val,val]
bar_x_lst.append(bar_x_lst[-1]+bar.get_width())
bar_y_lst.append(bar_y_lst[-1])
bar_y_lst = [i/2 for i in bar_y_lst]
plt.plot(bar_x_lst,bar_y_lst , c= 'red' )