首页 > 解决方案 > 如何使用子图摆脱 y 轴上不必要的值?

问题描述

我有这两个数据库(df2020 和 data2020):

df1

df2

我用这段代码做了两个子图:

f, axs = plt.subplots(2,2,figsize=(15,5))

    
X1 = df2020['month']
Y1 = df2020['notes']
ticks = ['1', '2', '3', '4', '5']

ax = f.add_subplot(121)
ax.bar(X1, Y1, facecolor = '#9999ff', edgecolor = 'white')
plt.setp(ax.get_xticklabels(), rotation=45)
ax.set_ylabel('Ratings')
ax.set_title('Evolution des notes durant 2020');

    
for x,y in zip(X1,Y1):
    plt.text(x, y, y, ha='center', va= 'bottom')

X2 = data2020['month']
Y2 = data2020['comms']

ax2 = f.add_subplot(122)
ax2.bar(X2, Y2, facecolor = '#9999ff', edgecolor = 'white')
plt.setp(ax2.get_xticklabels(), rotation=45)
ax2.set_ylabel('Ratings')
ax2.set_title('Evolution du nombre de commentaires durant 2020');

    
for x,y in zip(X2,Y2):
    plt.text(x, y, y, ha='center', va= 'bottom')

这是输出:

石墨

但正如你所看到的,这张图有一个小问题,我有点理解为什么。在 x 轴(0.0 到 1.0)和 y 轴(0.0 到 1.0)和右侧一个 0 以及两个图形上都有某种前通用值。我不知道如何摆脱它们,我试图指定set_ylimset_ytickslabel仅更改我想保留的值(y 轴上的 0.0 到 5.0 值和 x 轴上的日期)。

我应该怎么做才能解决这个问题?

谢谢 :)

标签: pythonpython-3.xmatplotlibaxissubplot

解决方案


您首先使用 创建四个(空)子图f, axs = plt.subplots(2, 2, figsize=(15, 5)),然后使用在它们之上创建新的子图f.add_subplot

您可以立即使用axs创建的变量plt.subplots来绘制数据,之后您不需要明确创建子图。请注意,您当前正在创建一个 2×2 网格的子图,而您想要创建一个 1×2 网格(行)。

f, axs = plt.subplots(1, 2, figsize=(15, 5))

X1 = df2020['month']
Y1 = df2020['notes']
ticks = ['1', '2', '3', '4', '5']

axs[0].bar(X1, Y1, facecolor = '#9999ff', edgecolor = 'white')
plt.setp(axs[0].get_xticklabels(), rotation=45)
axs[0].set_ylabel('Ratings')
axs[0].set_title('Evolution des notes durant 2020')

for x,y in zip(X1,Y1):
    axs[0].text(x, y, y, ha='center', va= 'bottom')

X2 = data2020['month']
Y2 = data2020['comms']

axs[1].bar(X2, Y2, facecolor = '#9999ff', edgecolor = 'white')
plt.setp(axs[1].get_xticklabels(), rotation=45)
axs[1].set_ylabel('Ratings')
axs[1].set_title('Evolution du nombre de commentaires durant 2020')

for x,y in zip(X2,Y2):
    axs[1].text(x, y, y, ha='center', va= 'bottom')

推荐阅读