我有一个用 Pandas 创建的现有情节,如下所示:
df['myvar'].plot(kind='bar')
y 轴的格式为 float ,我想将 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: using percentage on x axis
最佳答案
这晚了几个月,但我创建了 PR#6251使用 matplotlib 添加一个新的 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
、symbol
。 xmax
允许您设置对应于轴上 100% 的值。如果您有从 0.0 到 1.0 的数据并且您希望将其从 0% 显示到 100%,这很好。只需执行 PercentFormatter(1.0)
.
另外两个参数可以设置小数点后的位数和符号。它们分别默认为 None
和 '%'
。 decimals=None
将根据您显示的轴数自动设置小数点数。
更新
PercentFormatter
在 2.1.0 版本中被引入到 Matplotlib 中。
关于python - 将 y 轴格式化为百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31357611/