繁体   English   中英

如何使用 Python 一起绘制密度 plot 和条形 plot?

[英]How to draw density plot and bar plot together using Python?

假设我有这样的数据:

c1=pd.DataFrame({'Num1':[1,2,3,4],
                 'Counts':[5,1,7,10]})
c2=pd.DataFrame({'Num2':[3,4,5,6],
                 'Counts':[3,5,2,8]})
c12=pd.DataFrame({'Num1':[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4],
                  'Num2':[3,4,5,6,3,4,5,6,3,4,5,6,3,4,5,6],
                  'Counts':[2,3,1,3,4,5,1,6,7,2,5,10,4,8,2,9]})

c1 有 Num1,Counts 表示 c1 中的数字在数据集中出现的次数。 例如,1 出现 5 次。 c2也是如此。 c12 表示 Num1 和 Num2 出现的次数。 例如,Num1=1 和 Num2=3 出现 2 次。

我想画这样一个plot:

在此处输入图像描述

x 轴是 c1 中的 Num1,y 轴是 Num2。 条形图 plot 表示 c1 或 c2 中的计数。 散点图 plot 表示 c12 中的计数。 在分散 plot 中,点大小是计数。

我该如何使用 Python 来做到这一点?

您可以在matplotlib中组合三个图:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(5, 5))
fig.add_axes([0, 0, 0.8, 0.8])
plt.scatter(x=c12['Num1'], y=c12['Num2'], s=c12['Counts'] * 20)
plt.xlabel('Num1')
plt.ylabel('Num2')
plt.xticks(range(10))
plt.yticks(range(10))
plt.ylim(0, 10)
plt.xlim(0, 10)

# first barplot
fig.add_axes([0, 0.8, 0.8, 0.2])
plt.bar(x=c1['Num1'], height=c1['Counts'])
plt.axis('off')
plt.xlim(0, 10)

# second barplot
fig.add_axes([0.8, 0, 0.2, 0.8])
plt.barh(y=c2['Num2'], width=c2['Counts'])
plt.axis('off')
plt.ylim(0, 10)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM