【问题标题】:barplot labels to show full numbers instead of scientific formula [duplicate]条形图标签显示完整数字而不是科学公式[重复]
【发布时间】:2022-02-06 21:04:42
【问题描述】:

我正在使用this kaggle dataset 执行我的数据分析。 我将'course_students_enrolled' 列值转换为整数。 当我绘制学生人数最多的课程时,我得到一个数字,其中代表 1M 以上值的条形标签出现在公式中,如1.3e+06,而不是显示完整数字。图表上方的数字也是如此。 这是我的情节代码:

popularity_filt = (main_df['course_students_enrolled'].sort_values(ascending=False))
most_pop_courses = main_df.iloc[popularity_filt.index][:10]
course_titles = most_pop_courses['title'].to_list()
data = most_pop_courses[['title','course_students_enrolled']]
sns.set_context(font_scale=3, rc={'font.size':12, 'axes.labelsize':20})
sns.set_style('darkgrid')
palette = sns.color_palette(palette="Greens_d", n_colors=len(data))
plt.figure(figsize=(12,6))
ax = sns.barplot(x='title', y='course_students_enrolled', data=data, palette=np.array(palette[::-1]));
ax.set_xticklabels(course_titles, rotation=40, ha='right')
ax.bar_label(ax.containers[0]);

plt.show()

有没有办法显示完整的数字?

【问题讨论】:

标签: python matplotlib seaborn bar-chart


【解决方案1】:

您可以使用 f-string 将其转换为适当的字符串:

ax.bar_label(ax.containers[0], labels=[f'{x.get_height():.0f}' for x in ax.containers[0]])

【讨论】:

  • 您的建议中应该存在一些语法问题。我试图更改引号并将“f”放在引号之前,但这对我不起作用。你能检查它是否像你写的那样工作吗?
  • 我改变了位置,使 f 在引号之外。
  • python 不接受您建议中的引号。更改报价后仍然无法正常工作。这是我得到的 qhat:TypeError: unsupported format string passed to Rectangle.__format__
  • 我已经修改了答案。
  • 直接设置格式似乎更有意义:ax.bar_label(ax.containers[0], fmt='%.0f')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多