Nco*_*ody 5 python matplotlib bar-chart seaborn
如何更改 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
Run Code Online (Sandbox Code Playgroud)
data = pd.read_csv('COVID19_state.csv')
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
输出:
我找到了两个选项,第一个选择默认值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])
Run Code Online (Sandbox Code Playgroud)
第二种方法定义一个自定义格式化程序,它除以 1e6 并附加“million”:
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])
Run Code Online (Sandbox Code Playgroud)
我在 中找不到ScalarFormatter
将 1e6 替换为“million”的方法,但我确信 matplotlib 中有一种方法可以让您做到这一点(如果您确实愿意)。
编辑:使用ax.text
:
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])
Run Code Online (Sandbox Code Playgroud)
当然,如果您已经有一个标签,那么将其包含在那里可能更有意义,这至少是我会做的:
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")
Run Code Online (Sandbox Code Playgroud)
如果您确保您的数据已经以百万为单位且介于 和 之间1e-4
(1e5
超出此范围,科学记数法将启动),您可以省略最后两个方法中设置格式化程序的整个部分,只需将ax.text(0, 1.05, "in millions", transform = ax.transAxes, ha = "left", va = "top")
或添加ax.set_ylabel("interesting_unit in millions")
到您的代码中。您仍然需要为其他两种方法设置格式化程序。
归档时间: |
|
查看次数: |
7212 次 |
最近记录: |