如何使用Python将密度图和条形图绘制在一起?

时间:2019-10-06 12:20:39

标签: python count histogram heatmap scatter

假设我有这样的数据:

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,计数表示c1中的数字出现在数据集中的次数。例如,发生1次5次。 c2也是如此。 c12表示Num1和Num2发生多少次。例如,Num1 = 1和Num2 = 3出现2次。

我想画这样的图:

enter image description here

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

如何使用Python做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以在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)

enter image description here