将y轴格式化为百分比 [英] Format y axis as percent

查看:147
本文介绍了将y轴格式化为百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现成的地块是用这样的熊猫创建的:

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

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

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

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轴设置为百分比格式?

这是我找到的解决方案,但要求我重新定义图:

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

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

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

推荐答案

这已经晚了几个月,但是我创建了 PR#6251 与matplotlib一起添加新的PercentFormatter类.对于此类,您只需要一行就可以重新格式化轴(如果算上matplotlib.ticker的导入,则需要两行):

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

import ...
import matplotlib.ticker as mtick

ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

PercentFormatter()接受三个参数,xmaxdecimalssymbol. xmax允许您设置对应于轴上100%的值.如果数据的范围是0.0到1.0,并且要显示的范围是0%到100%,那么这很好.只需PercentFormatter(1.0).

PercentFormatter() accepts three arguments, xmax, decimals, symbol. xmax allows 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).

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

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

更新

PercentFormatter . 0.

这篇关于将y轴格式化为百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆