use*_*824 1 python pandas density-plot
我想创建一个类似于下面所附的图的图。
我的数据框是按以下格式构建的:
Playlist Type Streams
0 a classical 94
1 b hip-hop 12
2 c classical 8
Run Code Online (Sandbox Code Playgroud)
“流行度”类别可以用“流”代替 - 唯一的是流变量具有很高的值方差(从 0 到 10,000+),因此我认为密度图可能看起来很奇怪。
然而,我的第一个问题是,当按“类型”列分组然后创建密度图时,如何在 Pandas 中绘制与此类似的图表。
我尝试了各种方法,但没有找到一个好的方法来确立我的目标。
为了增强@Student240的答案,您可以使用seaborn库,它可以轻松适应“核密度估计”。换句话说,拥有与您的问题类似的平滑曲线,而不是合并的直方图。这是通过KDEplot类完成的。相关的绘图类型是distplot,它给出 KDE 估计值,但也显示直方图箱。
我的答案的另一个区别是在 matplotlib/seaborn 中使用显式的面向对象方法。这涉及到最初声明一个图形和轴对象,而plt.subplots()不是隐式方法fig.hist。有关更多详细信息,请参阅这个非常好的教程。
import matplotlib.pyplot as plt
import seaborn as sns
## This block of code is copied from Student240's answer:
import random
categories = ['classical','hip-hop','indiepop','indierock','jazz'
,'metal','pop','rap','rock']
# NB I use a slightly different random variable assignment to introduce a bit more variety in my random numbers.
df = pd.DataFrame({'Type':[random.choice(categories) for _ in range(1000)],
'stream':[random.normalvariate(i,random.randint(0,15)) for i in
range(1000)]})
###split the data into groups based on types
g = df.groupby('Type')
## From here things change as I make use of the seaborn library
classical = g.get_group('classical')
hiphop = g.get_group('hip-hop')
indiepop = g.get_group('indiepop')
indierock = g.get_group('indierock')
fig, ax = plt.subplots()
ax = sns.kdeplot(data=classical['stream'], label='classical streams', ax=ax)
ax = sns.kdeplot(data=hiphop['stream'], label='hiphop streams', ax=ax)
ax = sns.kdeplot(data=indiepop['stream'], label='indiepop streams', ax=ax)
# for this final one I use the shade option just to show how it is done:
ax = sns.kdeplot(data=indierock['stream'], label='indierock streams', ax=ax, shade=True)
ax.set_xtitle('Count')
ax.set_ytitle('Density')
ax.set_title('KDE plot example from seaborn")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9960 次 |
| 最近记录: |