如何使用Python同时绘制密度图和条形图?

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 次。

我想画这样一个情节:

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

如何使用 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)