首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >试图组合条形图和线状图

试图组合条形图和线状图
EN

Stack Overflow用户
提问于 2022-09-02 22:28:24
回答 1查看 98关注 0票数 0

我想要创建一个合并的条形图和线状图,它们都在同一个图中,具有相同的x轴。它们都存在于同一数据格式中。结果只返回预期的条形图,但我不知道如何将线条图与条形图数据重叠。条形图的相关数据是“不搅动”和“大总计”。相关的线图数据是'0-3','4-11','12+。下面是一个例子,数据与当前的输出和预期的输出显示为两个图,我想结合在一起。

代码语言:javascript
运行
复制
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')

预期产出

代码语言:javascript
运行
复制
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')

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-02 22:53:43

使用ax参数,您可以将一个绘图传递给另一个

代码语言:javascript
运行
复制
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()

此外,我建议只向第一个地块添加地块配置,并在最后一个地块上添加标题和标签是避免不一致的良好做法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73588403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档