python - 我可以关闭 matplotlib 条形图中的科学记数法吗?

标签 python matplotlib scientific-notation ticker

我有一个看起来像我想要的样子的条形图,除了 y 轴上的科学记数法。

一些其他的解决方案包括使用

ax.yaxis.set_major_formatter(tick)

这没有用。此外,我尝试检查这是否是一个偏移问题,但它应该显示一个“+”号,但在这种情况下却没有。

每当我使用:

plt.ticklabel_format(style='plain')

我收到一条错误消息:

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\matplotlib\axes\_base.py", line 2831, in ticklabel_format
    self.xaxis.major.formatter.set_scientific(sb)
AttributeError: 'FixedFormatter' object has no attribute 'set_scientific'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Python/Projects/Kaggle 1.py", line 13, in <module>
    plt.ticklabel_format(style='plain')
  File "C:\Python\lib\site-packages\matplotlib\pyplot.py", line 2982, in ticklabel_format
    useMathText=useMathText)
  File "C:\Python\lib\site-packages\matplotlib\axes\_base.py", line 2856, in ticklabel_format
    "This method only works with the ScalarFormatter.")
AttributeError: This method only works with the ScalarFormatter.

我已经研究过这个 ScalarFormatter,但我无法弄清楚为什么它不起作用。我试图在代码中明确包含它,但它不起作用。

我使用的代码是:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv("100 Sales Records.csv")
df_new = df.groupby(['Region']).sum().sort_values("Total Profit", ascending=False)
regions = ('Sub-Saharan Africa', 'Europe', 'Asia', 'Middle East and North Africa', 'Australia and Oceania', 'Central America and the Caribbean', 'North America')
profit = df_new['Total Profit']
y_pos = np.arange(len(profit))

plt.bar(y_pos, profit)
plt.xticks(y_pos, regions)
plt.ticklabel_format(style='plain')
plt.title('Sum of Sales')

plt.show()

图表目前看起来像这样:

enter image description here

最佳答案

您可以使用 matplotlib.tickerFuncFormatter 来更新当前绘图上的刻度。在下面的示例中,刻度使用自定义 scientific_formatter 进行更新,我将其定义为使用 2 个精度数字更新科学记数法中的刻度 - %2E

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

profit = pd.Series(np.random.randint(1e2, size=5))
ax = profit.plot(kind="bar")

def scientific(x, pos):
    # x:  tick value - ie. what you currently see in yticks
    # pos: a position - ie. the index of the tick (from 0 to 9 in this example)
    return '%.2E' % x

scientific_formatter = FuncFormatter(scientific)
ax.yaxis.set_major_formatter(scientific_formatter)

关于python - 我可以关闭 matplotlib 条形图中的科学记数法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165569/

相关文章:

python - 回文问题 lambda 和 key 的使用

Python:一个月的第三个星期五

python - 鼠兔与 celery ,连接已关闭

python - 存储这些向量但在 Python 中使用哪种数据结构

Python:复制 basemap 或从图中删除数据

java - 将具有负标度的 BigDecimal 转换为正标度

python - 如何随机化 if/elif 语句的顺序?

python - 如何将彩色图显示为从数组实时生成的 pygame 表面?

parsing - 从文本文件lua中解析科学数字

r - 如何摆脱 cut() 生成的因子的科学记数法