我想要创建一个合并的条形图和线状图,它们都在同一个图中,具有相同的x轴。它们都存在于同一数据格式中。结果只返回预期的条形图,但我不知道如何将线条图与条形图数据重叠。条形图的相关数据是“不搅动”和“大总计”。相关的线图数据是'0-3','4-11','12+。下面是一个例子,数据与当前的输出和预期的输出显示为两个图,我想结合在一起。
df_rand = pd.DataFrame(np.random.randint(0,100,size=(10, 5)), columns=['No Churn', 'Grand Total', '0-3', '4-11', '12+'])
df_rand['Snapshot_Month'] = ['2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10']
plt.style.use('ggplot')
ax = df_rand.plot(x='Snapshot_Month', kind='bar', title ="Cohort",figsize=(20,10),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('No Churn')
ax.set_ylabel('Amount')
预期产出
plt.style.use('ggplot')
ax = df_rand[['Snapshot_Month', 'No Churn', 'Grand Total']].plot(x='Snapshot_Month', kind='bar', title ="Cohort",figsize=(20,5),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('Amount')
###combined with###
plt.style.use('ggplot')
ax = df_rand[['Snapshot_Month', '0-3', '4-11', '12+']].plot(x='Snapshot_Month', kind='line', title ="Cohort",figsize=(20,5),legend=True, fontsize=12)
ax.set_xlabel('Snapshot_Month')
ax.set_ylabel('Amount')
发布于 2022-09-02 22:53:43
使用ax
参数,您可以将一个绘图传递给另一个
plt.style.use('ggplot')
# adding plot configurations to the first plot
ax1 = df_rand[['Snapshot_Month', 'No Churn', 'Grand Total']].plot(x='Snapshot_Month', kind='bar', figsize=(20,5), legend=True, fontsize=12)
# adding parameter ax with value ax1
ax2 = df_rand[['Snapshot_Month', '0-3', '4-11', '12+']].plot(x='Snapshot_Month', kind='line', legend=True, ax=ax1)
# assigning labels and titles to the last plot
ax2.set_title('Cohort')
ax2.set_xlabel('Snapshot_Month')
ax2.set_ylabel('Amount')
plt.show()
此外,我建议只向第一个地块添加地块配置,并在最后一个地块上添加标题和标签是避免不一致的良好做法。
https://stackoverflow.com/questions/73588403
复制相似问题