Python 将 y 轴格式化为百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31357611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:52:13  来源:igfitidea点击:

Format y axis as percent

pythonpandasmatplotlibplot

提问by Chris

I have an existing plot that was created with pandas like this:

我有一个用熊猫创建的现有图,如下所示:

df['myvar'].plot(kind='bar')

The y axis is format as float and I want to change the y axis to percentages. All of the solutions I found use ax.xyz syntax and I can only place code below the line above that creates the plot(I cannot add ax=ax to the line above.)

y 轴的格式为浮点数,我想将 y 轴更改为百分比。我发现的所有解决方案都使用 ax.xyz 语法,我只能将代码放在上面创建绘图的行下方(我不能将 ax=ax 添加到上面的行。)

How can I format the y axis as percentages without changing the line above?

如何在不更改上面的行的情况下将 y 轴格式化为百分比?

Here is the solution I found but requires that I redefine the plot:

这是我找到的解决方案,但需要我重新定义情节

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

Link to the above solution: Pyplot: using percentage on x axis

链接到上述解决方案:Pyplot:在 x 轴上使用百分比

采纳答案by Mad Physicist

This is a few months late, but I have created PR#6251with matplotlib to add a new PercentFormatterclass. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker):

这已经晚了几个月,但我已经用 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()accepts three arguments, xmax, decimals, symbol. xmaxallows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0).

PercentFormatter()接受三个参数,xmax, decimals, symbolxmax允许您设置对应于轴上 100% 的值。如果您的数据范围从 0.0 到 1.0,并且您希望将其显示在 0% 到 100% 之间,这很好。就做PercentFormatter(1.0)

The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to Noneand '%', respectively. decimals=Nonewill automatically set the number of decimal points based on how much of the axes you are showing.

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

Update

更新

PercentFormatterwas introduced into Matplotlib proper in version 2.1.0.

PercentFormatter在 2.1.0 版中被引入到 Matplotlib 中。

回答by Jianxun Li

pandas dataframe plot will return the axfor you, And then you can start to manipulate the axes whatever you want.

pandas 数据框图将为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])

enter image description here

在此处输入图片说明

回答by erwanp

Jianxun's solution did the job for me but broke the y value indicator at the bottom left of the window.

Jianxun的解决方案为我完成了这项工作,但打破了窗口左下角的 y 值指示器。

I ended up using FuncFormatterinstead (and also stripped the uneccessary trailing zeroes as suggested here):

我最终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))) 

Generally speaking I'd recommend using FuncFormatterfor label formatting: it's reliable, and versatile.

一般来说,我建议FuncFormatter用于标签格式:它可靠且用途广泛。

enter image description here

在此处输入图片说明

回答by np8

For those who are looking for the quick one-liner:

对于那些正在寻找快速单线的人:

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

Or if you are using Latexas the axis text formatter, you have to add one backslash '\'

或者,如果您使用Latex作为轴文本格式化程序,则必须添加一个反斜杠 '\'

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

回答by Dr. Arslan

I propose an alternative method using seaborn

我提出了一种替代方法,使用 seaborn

Working code:

工作代码:

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)

enter image description here

在此处输入图片说明