【问题标题】:Setting y-axis labels, range, limit on bar graph python在条形图python上设置y轴标签、范围、限制
【发布时间】:2020-09-20 01:01:40
【问题描述】:

所以我试图绘制这个数据框的条形图,团队由字符串组成,提及由整数组成。试图在 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 轴上的间隔是整数/整数而不是小数/浮点数?

【问题讨论】:

  • 您能否提供其他人运行您的代码所需的最少数据量。
  • 添加了额外的数据
  • from matplotlib.ticker import MaxNLocatorplt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))。见Matplotlib: How to force integer tick labels?

标签: python numpy matplotlib plot graph


【解决方案1】:

其中一个可能的选项是使用 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()

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

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多