繁体   English   中英

Matplotlib子图

[英]Matplotlib Subplots

我有以下代码可以生成两个图表,但是我想使用子图将它们并排放置。 我怎样才能做到这一点?

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()

我开始将add_subplot与以下代码一起使用,但是不确定如何将以上代码添加到图中。 任何帮助,将不胜感激!

fig = plt.figure()

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

创建具有两个子图的图形

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

并绘制相应的轴对象,例如

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')

并因此axs[1]p1

请注意, axes由Method对象的更新,例如,标签ax.set_xlabel而不是plt.xlabel 您可以在此处找到更多信息: https : //matplotlib.org/api/axes_api.html#matplotlib.axes.Axes

希望这可以帮助。

暂无
暂无

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

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