为了账号安全,请及时绑定邮箱和手机立即绑定

我可以在 matplotlib 条形图中转换科学记数法吗?

我可以在 matplotlib 条形图中转换科学记数法吗?

慕妹3242003 2021-10-10 13:56:40
我有一个条形图,看起来像我想要的样子,除了 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 pdimport numpy as npimport matplotlib.pyplot as pltdf = 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()该图表目前如下所示:
查看完整描述

2 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

您可以使用FuncFormatter的matplotlib.ticker更新蜱,你想对你目前的阴谋。在我下面的示例中,刻度是使用 customscientific_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)


查看完整回答
反对 回复 2021-10-10
?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

错误是因为plt.ticklabel_format(style='plain')默认情况下将两个轴都设置为 ,plain而您的 xticks 是自定义的并且不能是plain

用于plt.ticklabel_format(axis="y", style='plain')单独设置 y 轴。


查看完整回答
反对 回复 2021-10-10
  • 2 回答
  • 0 关注
  • 1085 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号