在条形图python上设置y轴标签,范围和限制

时间:2020-09-20 01:01:40

标签: python numpy matplotlib plot graph

因此,我试图绘制此数据框的条形图,“团队”由字符串组成,“提及”由int组成。尝试在x轴上绘制团队,并在y轴上绘制提及。但是我在y轴标签上遇到了问题,增量和标签以小数表示,我希望它们以整数/整数表示:

top_5_teams = ['England', 'France', 'Ireland', 'Italy', 'Wales']
top_5_team_mentions = [20, 11, 13, 6, 11]
df4 = pd.DataFrame({"Team":top_5_teams,
                      'Number of Times Mentioned':top_5_team_mentions})
df4 = df4.sort_values("Number of Times Mentioned", ascending=False)

df4_team = df4.iloc[:,0]
df4_mentions = df4.iloc[:,1]
plt.bar(arange(len(df4_team)),df4_mentions)
plt.xticks(arange(len(df4_team)),team,rotation=30)
plt.show()

这是我的图表: enter image description here

我想基于arange()这样的变量而不是像20或25这样的单个数字来执行此操作,因此我的代码可以与任何数据帧一起使用。 那么如何更改它,以便y轴上的间隔是整数/整数,而不是小数/浮点数?

1 个答案:

答案 0 :(得分:0)

一种可能的选择是使用 MultipleLocator ,您可以在其中指定 y 值的倍数,其中要打印刻度 ({import matplotlib.ticker as tck是必需的。)

另一个细节是,当您执行以下操作时,绘图代码可以更简洁:

  • 将列设置为以 x 轴作为索引,
  • 仅从 DataFrame 或其列之一创建图。

因此,在创建DataFrame之后,只需运行:

df4.set_index('Team').plot.bar(legend=None, rot=30)
plt.ylabel('Times mentioned')
plt.gca().yaxis.set_major_locator(tck.MultipleLocator(5))
plt.show()

对于您的数据,我得到以下图表:

enter image description here