簡體   English   中英

如何在 matplotlib 中使 y 軸上的數字顯示以百萬為單位的值而不是科學計數法?

[英]How do I make the numbers on the y-axis show values in millions instead of in scientific notation in matplotlib?

如何更改 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()

Output:這個情節

我找到了兩個選項,第一個獲取默認的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")

斧頭文本

當然,如果你已經有一個 label 可能更有意義將它包含在其中,這就是我至少會做的:

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之間(超出此范圍, 科學記數法將生效),您可以省略最后兩種方法中設置格式化程序的整個部分,只需添加ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top")ax.set_ylabel("interesting_unit in millions")到您的代碼。 您仍然需要為其他兩種方法設置格式化程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM