如何使用matplotilib在子图中设置x_ticks旋转?

我正在使用matplotlib子图并排创建两个图。 这是我正在使用的代码

fig,(ax0,ax1) = py.subplots(nrows=1,ncols=2,sharey=True,figsize=(16,6))
fig.suptitle('Trips percentage per daira (for the top 10 dairas)',size = 16)

py.xticks(rotation = 90)
ax = sns.barplot(x = df.p_daira.value_counts().nlargest(10).index,y = df.p_daira.value_counts().nlargest(10) / df.shape[0] * 100,ax = ax0)
ax.set(xlabel='Pickup Daira',ylabel='Trips percentage')
ax.set_xticks(rotation=90)

#py.xticks(rotation=90)
ax = sns.barplot(x = df.d_daira.value_counts().nlargest(10).index,y = df.d_daira.value_counts().nlargest(10)/df.shape[0] * 100,ax = ax1)
ax.set(xlabel='Dropoff Daira',ylabel='Trips percentage')

py.show()

这是我得到的结果: Image

即使我将x_ticks旋转设置为90度,它也仅适用于第二个绘图!

有没有办法解决这个问题?

levisor 回答:如何使用matplotilib在子图中设置x_ticks旋转?

在您编写py.xticks(rotation = 90)时,我们必须假设您导入了matplotlib.pyplot as py(这是可能的,但通常缩写为import matplotlib.pyplot as plt)。

但是,请注意,使用pyplot(在您的情况下为py)的方法,您总是会自动引用当前有效轴,通常是最后创建的一个。

如果要显式调用某些轴的函数,请使用它们的对象表示法,例如

ax1.xaxis.set_tick_params(rotation=90)
ax2.xaxis.set_tick_params(rotation=90)

请注意,如果您想知道在创建更多的3x3或更高的子图时这将导致什么,您宁愿将它们全部存储在像这样的数组中

import matplotlib.pyplot as plt
fig,axs = plt.subplots(3,3)

,然后通过索引数组来访问单轴,例如

axs[0,0].plot(x,y)
axs[1,0].plot(z)

for ax in axs.flatten():
    ax.xaxis.set_tick_params(rotation=90)
本文链接:https://www.f2er.com/3127723.html

大家都在问