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
对象更新,例如,标签由方法 ax.set_xlabel
而不是 plt.xlabel
更新。您可以在此处找到更多信息:https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes。
希望对您有所帮助。
我有以下代码可以生成两个图表,但我想使用子图将它们并排放置。我该怎么做?
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
对象更新,例如,标签由方法 ax.set_xlabel
而不是 plt.xlabel
更新。您可以在此处找到更多信息:https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes。
希望对您有所帮助。