我有一个现有的用熊猫创建的图,像这样:

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轴上的百分比


熊猫数据框架图将为你返回斧头,然后你可以开始操纵任何你想要的斧头。

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])


简勋的解决方案为我解决了这个问题,但破坏了窗口左下角的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进行标签格式化:它是可靠的,通用的。


这迟了几个月,但我已经用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,小数,符号。Xmax允许您设置轴上对应于100%的值。如果您有从0.0到1.0的数据,并且您想要显示从0%到100%的数据,这是很好的方法。只需使用PercentFormatter(1.0)。

另外两个参数允许您设置小数点和符号之后的位数。它们分别默认为None和'%'。decimals=None将根据您所显示的轴的大小自动设置小数点的数目。

更新

在2.1.0版中,Matplotlib正式引入了PercentFormatter。


对于那些正在寻找简单语句的人来说:

plt.gca().set_yticklabels([f'{x:.0%}' for x in plt.gca().get_yticks()]) 

这个假设

导入:从matplotlib导入pyplot作为PLT Python >=3.6用于f-String格式。对于旧版本,替换f'{x:。0}'和'{:.0%}'.format(x)


我建议另一种方法,用海运

工作代码:

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)


我来晚了,但我刚刚意识到这一点:对于那些不使用轴而只是子图的人来说,ax可以用plt.gca()代替。

呼应@疯狂物理学家的回答,使用软件包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

基于@erwanp的答案,你可以使用Python 3的格式化字符串字面值,

x = '2'
percentage = f'{x}%' # 2%

在FuncFormatter()中,并与lambda表达式结合。

所有的包装:

ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))

你可以在一行中完成,而不需要导入任何东西: 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的一部分。但是你也可以做plt。FuncFormatter作为快捷方式。


如果符号在0到1之间,另一个一行解:

plt.yticks(plt.yticks()[0], ['{:,.0%}'.format(x) for x in plt.yticks()[0]])