将y轴格式化为百分比

Chr*_*ris 86 python plot matplotlib pandas

我有一个用pandas创建的现有情节,如下所示:

df['myvar'].plot(kind='bar')
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

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

Jia*_* Li 117

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])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 一旦以交互方式平移/缩放图形,这将产生不希望的效果 (5认同)
  • 比尝试使用`matplotlib.ticker`函数格式化器容易百万倍! (3认同)
  • @mpour 仅更改了 yticks 的标签,因此限制仍采用自然单位。设置 ax.set_ylim(0, 1) 就可以了。 (2认同)

erw*_*anp 69

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))) 
Run Code Online (Sandbox Code Playgroud)

一般来说,我建议使用FuncFormatter标签格式:它可靠,功能多样.

在此输入图像描述

  • 您可以更简化代码:`ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format))`.AKA不需要lambda,让格式做工作. (14认同)
  • @DChaps`' {0:.0%}'.format`创建[格式化函数](https://docs.python.org/3.6/library/string.html#format-examples).冒号前面的`0`告诉格式化程序用传递给函数的第一个参数替换花括号及其内容.冒号后面的部分`.0%`告诉格式化程序如何呈现值.`.0`指定0个小数位,`%`指定渲染为百分比. (2认同)

Mad*_*ist 64

这是几个月的晚了,但是我用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())
Run Code Online (Sandbox Code Playgroud)

PercentFormatter()接受三个参数,xmax,decimals,symbol.xmax允许您设置轴上对应于100%的值.如果您有0.0到1.0的数据并且想要将其显示在0%到100%之间,这很好.做吧PercentFormatter(1.0).

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

  • 等不及发布了.我想知道为什么这不是微不足道的.谢谢你补充一下. (2认同)
  • 回答得好!就我而言,我使用“plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter())”来避免首先保存“ax”图。 (2认同)
  • @MadPhysicist - 因为 1.0=100%,所以它们是相同的*数字*!就好像使用“x1e6”更改为科学记数法将“1000000”更改为“1000000x1e6”......它改变了数字。我从来没有想过,这肯定是 erwanp 的答案按预期工作而不需要任何进一步的输入参数的原因,如“PercentFormatter”中所示。拥有 `xmax` 的进一步灵活性可能很好,但默认值显然是错误的,它不是“不转换”。我肯定错过了什么... (2认同)

np8*_*np8 27

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

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

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

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


小智 12

我迟到了,但我才意识到这一点:对于那些不使用轴而只是子图的人,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
Run Code Online (Sandbox Code Playgroud)


Dr.*_*lan 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


1''*_*1'' 5

您可以在一行中完成此操作,而无需导入任何内容: plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{}%'.format))

如果你想要整数百分比,你可以这样做: plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format))

您可以使用ax.yaxisplt.gca().yaxisFuncFormatter仍然是 的一部分matplotlib.ticker,但您也可以plt.FuncFormatter作为快捷方式执行。