【问题标题】:How do I make the numbers on the y-axis show values in millions instead of in scientific notation in matplotlib?如何使 y 轴上的数字显示以百万为单位的值,而不是 matplotlib 中的科学计数法?
【发布时间】:2021-04-23 18:47:43
【问题描述】:

如何更改 y 轴上的数字以显示 0 到 1700 万而不是 0 到 1.75 1e7?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pingouin as pg
import plotly
import plotly.express as px
data = pd.read_csv('COVID19_state.csv')
fig, ax = plt.subplots(figsize=(12,5))
ax = sns.barplot(x = 'State', y = 'Tested', data = data, color='blue');
ax.set_title('Tested by State')
ax.set_xticklabels(labels=data['State'], rotation=90)
ax.set_ylabel('Tested')
ax.set_xlabel('State')
plt.grid()
plt.show()

输出:

【问题讨论】:

  • 我的回答对你有帮助吗,还是你还在寻找不同的东西?
  • 是的!这很有帮助!正在尝试找到正确的方式来写感谢!

标签: python matplotlib seaborn bar-chart


【解决方案1】:

我找到了两个选项,第一个获取默认matplotlib.ticker.ScalarFormatter并关闭科学记数法:

fig, ax = plt.subplots()
ax.yaxis.get_major_formatter().set_scientific(False)
ax.yaxis.get_major_formatter().set_useOffset(False)
ax.plot([0, 1], [0, 2e7])

第二种方法定义了一个自定义格式化程序,它除以 1e6 并附加“百万”:

from matplotlib.ticker import NullFormatter

def formatter(x, pos):
    return str(round(x / 1e6, 1)) + " million"

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])

我在ScalarFormatter 中找不到将 1e6 替换为“百万”的方法,但我确信 matplotlib 中有一个方法可以让您在需要时做到这一点。


编辑:使用ax.text

from matplotlib.ticker import NullFormatter

def formatter(x, pos):
    return str(round(x / 1e6, 1))

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])
ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top")

当然,如果您已经有了一个标签,那么在其中包含它可能更有意义,我至少会这样做:

from matplotlib.ticker import NullFormatter

def formatter(x, pos):
    return str(round(x / 1e6, 1))

fig, ax = plt.subplots()
ax.yaxis.set_major_formatter(formatter)
ax.yaxis.set_minor_formatter(NullFormatter())
ax.plot([0, 1], [0, 2e7])
ax.set_ylabel("interesting_unit in millions")

如果您确定您的数据已经以百万计并且在1e-41e5 之间(在此范围之外scientific notation will kick in),您可以省略在最后两个方法中设置格式化程序的整个部分,只需添加ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top")ax.set_ylabel("interesting_unit in millions") 到您的代码。您仍然需要为其他两种方法设置格式化程序。

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多