简体   繁体   English

Matplotlib子图

[英]Matplotlib Subplots

I have the following code that works to produce two charts, but I would like to use subplots to put them side by side. 我有以下代码可以生成两个图表,但是我想使用子图将它们并排放置。 How can I do that? 我怎样才能做到这一点?

p1 = df1.var1.value_counts(normalize=True).sort_index()
p2 = df2.var2.value_counts(normalize=True).sort_index()

p2.plot(kind='barh').invert_yaxis()
plt.xlim(0, 0.5)
plt.title('my title1')
plt.xlabel('% of Users')
plt.ylabel('my ylabel 1')
plt.show()

p1.plot(kind='barh').invert_yaxis()
plt.xlim(0, 0.5)
plt.title('my title 2')
plt.xlabel('% of Users')
plt.ylabel('my ylabel 2')
plt.show()

I started using add_subplot with the following code, but not sure how I can add the the above code into fig. 我开始将add_subplot与以下代码一起使用,但是不确定如何将以上代码添加到图中。 Any help would be appreciated! 任何帮助,将不胜感激!

fig = plt.figure()

fig1 = fig.add_subplot(121)
fig2 = fig.add_subplot(122)

Create a figure with two subplots 创建具有两个子图的图形

fig, axs = plt.subplots(ncols=2)

and plot in the according axes objects, eg, 并绘制相应的轴对象,例如

p2.plot(kind='barh', ax=axs[0]).invert_yaxis()
axs[0].set_xlim(0, 0.5)
axs[0].set_title('my title1')
axs[0].set_xlabel('% of Users')
axs[0].set_ylabel('my ylabel 1')

and accordingly axs[1] for p1 . 并因此axs[1]p1

Note that the axes object updates, eg, the label by the method ax.set_xlabel instead of plt.xlabel . 请注意, axes由Method对象的更新,例如,标签ax.set_xlabel而不是plt.xlabel You can find more information here: https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes . 您可以在此处找到更多信息: https : //matplotlib.org/api/axes_api.html#matplotlib.axes.Axes

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM