如何使用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()

以下是我得到的结果:图像

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

有办法解决这个问题吗?

在编写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)

最新更新