在同一个图上绘制一个“hist”和“kde”的数据框 [英] Plotting a dataframe as both a 'hist' and 'kde' on the same plot
问题描述
我有一个熊猫数据框
与用户信息。我想将用户年龄作为 kind ='kde'
和 kind ='hist'
在同一个情节目前我有两个独立的地块。数据框架类似于:
I have a pandas dataframe
with user information. I would like to plot the age of users as both a kind='kde'
and on kind='hist'
on the same plot. At the moment I am able to have the two separate plots. The dataframe resembles:
member_df=
user_id Age
1 23
2 34
3 63
4 18
5 53
...
使用
ax1 = plt.subplot2grid((2,3), (0,0))
member_df.Age.plot(kind='kde', xlim=[16, 100])
ax1.set_xlabel('Age')
ax2 = plt.subplot2grid((2,3), (0,1))
member_df.Age.plot(kind='hist', bins=40)
ax2.set_xlabel('Age')
ax3 = ...
我明白 kind ='kde'
将给出y轴的频率,而 kind ='kde'
将给出累积分布,但是是否有一种组合两者并具有y-轴由频率表示?
I understand that the kind='kde'
will give me frequencies for the y-axis whereas kind='kde'
will give a cumulative distribution, but is there a way to combine both and have the y-axis be represented by the frequencies?
推荐答案
pd.DataFrame.plot()
返回它正在绘制的 ax
。你可以重复使用这个其他地块。
pd.DataFrame.plot()
returns the ax
it is plotting to. You can reuse this for other plots.
尝试:
ax = member_df.Age.plot(kind='kde')
member_df.Age.plot(kind='hist', bins=40, ax=ax)
ax.set_xlabel('Age')
示例
我先把 hist
放在背景中
另外,我把 kde
在 secondary_y
轴
import pandas as pd
import numpy as np
np.random.seed([3,1415])
df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))
ax = df.a.plot(kind='hist')
df.a.plot(kind='kde', ax=ax, secondary_y=True)
回复评论
使用 subplot 2grid
。只需重新使用 ax1
import pandas as pd
import numpy as np
ax1 = plt.subplot2grid((2,3), (0,0))
np.random.seed([3,1415])
df = pd.DataFrame(np.random.randn(100, 2), columns=list('ab'))
df.a.plot(kind='hist', ax=ax1)
df.a.plot(kind='kde', ax=ax1, secondary_y=True)
这篇关于在同一个图上绘制一个“hist”和“kde”的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!