Python - 将 2 个图绘制在一起 [英] Python - Plot 2 Plots together

查看:169
本文介绍了Python - 将 2 个图绘制在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单独的图表,我想将它们显示在同一个图上.

I have two graphs individually and I want to display them on the same plot.

这是我的情节 1 代码

This is my plot 1 code

ax1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 1")
plt.show()

这是我的剧情2代码,

ax2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax1.plot.bar(rot =0)
plt.xlabel("Cat Names")
plt.ylabel("Measures")
plt.title("Title 2")
plt.show()

现在,这会一个接一个地显示在不同的图表(图像)中.我如何才能在同一张图中显示这一点 - 在同一张图(图片)中一个在另一个下方.

Now, this gets shown in different graph (image) one after another. How Can I show this in the same graph - one below another in the same graph (image).

请帮助我.

这就是我正在尝试的

fig, axes = plt.subplots(nrows=2)
df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
ax1 = df1.plot.bar(rot =0)
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()
ax2 = df2.plot.bar(rot =0)
ax1.plt.bar(rot=0, ax=axes[0])
ax2.plt.bar(rot=0, ax=axes[1])
plt.show()

它对我不起作用.

推荐答案

你的变量命名有点不合常规. ax 通常用于matplotlib Axes对象.这里有一个数据框.

Your variable naming is a bit unconventional. ax typically is used for a matplotlib Axes object. Here you have a dataframe.

无论如何,您应该设置一个具有两个轴的图形. plt.subplots 是执行此操作的一种简便方法.它将返回图形和一个包含您创建的所有轴的数组.您甚至可以使用 sharex sharey 将轴设置为相等.在每个数据帧的绘图调用中使用轴对象:

Regardless, you should set up a figure with two axes. plt.subplots is an easy way to do this. It will return the figure and an array with all the axes that you create. You can even set the axis to be equal between the two with sharex and sharey. Use the axes objects in your plotting call for each dataframe:

df1= concatenated_data_cleaned.groupby(['Cat1', 'Cat2']).median()[['Measure']].unstack()
df2= concatenated_data_cleaned.groupby(['Cat2', 'Cat1']).median()[['Measure']].unstack()

fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True)
df1.plot.bar(rot=0, ax=axes[0])
df2.plot.bar(rot=0, ax=axes[1])
axes[0].set_title('Title 0')
axes[1].set_title('Title 1')
plt.show()

这篇关于Python - 将 2 个图绘制在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆