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

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

其他回答

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

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

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

工作代码:

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)

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

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

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

所有的包装:

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

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

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

我来晚了,但我刚刚意识到这一点:对于那些不使用轴而只是子图的人来说,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