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

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

问题描述

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

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

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

y 轴的格式为浮点数,我想将 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 轴上使用百分比

推荐答案

这已经晚了几个月,但我已经创建了 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 被引入 Matplotlib在 2.1.0 版本中正确.

PercentFormatter was introduced into Matplotlib proper in version 2.1.0.

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

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