将 y 轴格式设置为百分比
- 2025-02-28 08:22:00
- admin 原创
- 77
问题描述:
我有一个用熊猫创建的现有情节,如下所示:
df['myvar'].plot(kind='bar')
y 轴的格式为浮点数,我想将 y 轴更改为百分比。我找到的所有解决方案都使用 ax.xyz 语法,我只能将代码放在创建图的上面一行的下方(我无法将 ax=ax 添加到上面一行。)
如何在不改变上面的行的情况下将 y 轴格式化为百分比?
这是我找到的解决方案,但需要我重新定义情节:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mtick
data = [8,12,15,17,18,18.5]
perc = np.linspace(0,100,len(data))
fig = plt.figure(1, (7,4))
ax = fig.add_subplot(1,1,1)
ax.plot(perc, data)
fmt = '%.0f%%' # Format you want the ticks, e.g. '40%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
plt.show()
链接到上面的解决方案:Pyplot:在 x 轴上使用百分比
解决方案 1:
虽然晚了几个月,但我已经用 matplotlib 创建了PR#6251来添加一个新PercentFormatter
类。使用这个类,你只需要一行代码就可以重新格式化你的轴(如果算上导入的话,则需要两行matplotlib.ticker
):
import ...
import matplotlib.ticker as mtick
ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
PercentFormatter()
接受三个参数,,,xmax
。decimals
允许您设置对应于轴上 100% 的值。如果您有从 0.0 到 1.0 的数据并且想要从 0% 到 100% 显示它,那么这很有用。只需symbol
执行。xmax
`PercentFormatter(1.0)`
另外两个参数允许您设置小数点后的位数和符号。它们分别默认为None
和'%'
。decimals=None
将根据您显示的轴的数量自动设置小数点的数量。
更新
PercentFormatter
在 2.1.0 版本中被引入到 Matplotlib 中。
解决方案 2:
pandas dataframe plot 将为ax
您返回,然后您可以开始随意操作轴。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(100,5))
# you get ax from here
ax = df.plot()
type(ax) # matplotlib.axes._subplots.AxesSubplot
# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:,.2%}'.format(x) for x in vals])
解决方案 3:
Jianxun的解决方案对我来说起了作用,但却破坏了窗口左下方的 y 值指示器。
我最终使用了FuncFormatter
(并且按照这里的建议去掉了不必要的尾随零):
import pandas as pd
import numpy as np
from matplotlib.ticker import FuncFormatter
df = pd.DataFrame(np.random.randn(100,5))
ax = df.plot()
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
一般来说,我建议使用它FuncFormatter
来设置标签格式:它可靠且用途广泛。
解决方案 4:
对于那些正在寻找快速单行代码的人来说:
plt.gca().set_yticklabels([f'{x:.0%}' for x in plt.gca().get_yticks()])
或者,如果您已将matplotlib.axes.Axes
对象保存到变量中ax
:
ax.set_yticklabels([f'{x:.0f}%' for x in ax.get_yticks()])
这假设
进口:
from matplotlib import pyplot as plt
Python >=3.6 用于 f-String 格式。对于较旧的版本,请将其替换
f'{x:.0%}'
为'{:.0%}'.format(x)
解决方案 5:
我迟到了,但我刚刚意识到这一点:对于那些不使用斧头而只使用子图的人来说,ax
可以用 来代替。plt.gca()
呼应@Mad Physicist 的回答,使用该包PercentFormatter
将是:
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))
#if you already have ticks in the 0 to 1 range. Otherwise see their answer
解决方案 6:
我建议使用另一种方法seaborn
工作代码:
import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)
解决方案 7:
您可以在一行中完成此操作而无需导入任何内容:plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{}%'.format))
如果您想要整数百分比,您可以执行以下操作:plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format))
您可以使用ax.yaxis
或plt.gca().yaxis
。FuncFormatter
仍然是 的一部分matplotlib.ticker
,但您也可以将其plt.FuncFormatter
作为快捷方式。
解决方案 8:
根据@erwanp的回答,您可以使用 Python 3的格式化字符串文字,
x = '2'
percentage = f'{x}%' # 2%
内部FuncFormatter()
并与lambda表达式相结合。
全部包装:
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))
解决方案 9:
如果 yticks 介于 0 和 1 之间,则还有另一行解决方案:
plt.yticks(plt.yticks()[0], ['{:,.0%}'.format(x) for x in plt.yticks()[0]])
解决方案 10:
添加一行代码
ax.yaxis.set_major_formatter(ticker.PercentFormatter())
扫码咨询,免费领取项目管理大礼包!