2015-07-11 93 views
38

我有与熊猫这样创建的现有情节:格式Y轴为百分之

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

y轴是浮点格式,我想y轴改为百分比。所有我发现使用ax.xyz语法和我只能将高于线下的代码解决方案的创建情节(我不能添加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

回答

59

大熊猫据帧情节将返回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(['{:3.2f}%'.format(x*100) for x in vals]) 

enter image description here

+0

当您交互式地平移/缩放图形时,这会产生不希望的效果 – hitzg

+1

比尝试使用'matplotlib.ticker'函数格式化程序容易百万倍! – Jarad

37

Jianxun的解决方案做的工作对我来说却爆出在窗口的左下角的y值指标。

我结束了使用FuncFormatter,而不是(也剥夺了uneccessary尾随零的建议here):

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的标签格式:它的可靠,用途广泛。

enter image description here

+5

您可以更简化代码:'ax.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'。format))''。 AKA不需要lambda,让格式来完成这项工作。 –

+0

@DanielHimmelstein你能解释一下这个吗?特别在{}内部。不知道如何使用python格式将0.06变成6%。也很好的解决方案似乎比使用.set_ticklabels – DChaps

+1

@DChaps''{0:.0%}'更可靠。format'创建一个[格式化函数](https://docs.python.org/3.6/library/string.html #格式的例子)。冒号前面的“0”告诉格式化程序用传递给函数的第一个参数替换大括号及其内容。冒号后面的部分'.0%'告诉格式化程序如何呈现值。 “.0”指定0位小数,“%”指定以百分比表示。 –

16

这几月中下旬,但我已经创建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()接受三个参数,maxdecimalssymbolmax允许您设置轴上对应于100%的值。如果你的数据从0.0到1.0,并且你想从0%到100%显示,这很好。只要做PercentFormatter(1.0)

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

+2

不能等待发布。我想知道为什么这不是微不足道的。感谢您添加此。 – DanT

+0

@DanT。公关被接受进2.1版。不知道何时该发布,但可能在未来几个月。同时,您始终可以使用GitHub的版本。 –

+0

这是*正确*答案,但一年后,我们仍在等待matplotlib 2.1 ... – MinchinWeb

6

对于那些谁正在寻找快速的一行:

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

或者,如果你正在使用乳胶为轴心的文本格式,你必须添加一个反斜杠“\”

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