Pyplot:在x轴上使用百分比 [英] Pyplot: using percentage on x axis

查看:60
本文介绍了Pyplot:在x轴上使用百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于简单数字列表的折线图.默认情况下,对于绘制的每个值,x 轴只是 1 的增量.我想成为一个百分比,但不知道如何.因此,x 轴不是从 0 到 5,而是从 0% 到 100%(但保持合理间隔的刻度线.下面的代码.谢谢!

from matplotlib import pyplot as plt从mpl_toolkits.axes_grid.axislines导入子图数据= [8,12,15,17,18,18.5]fig=plt.figure(1,(7,4))ax=子图(图111)fig.add_subplot(ax)plt.plot(数据)

解决方案

这已经晚了几个月,但我已经创建了 PR#6251 使用 matplotlib 添加新的 PercentFormatter 类.使用这个类,您可以执行以下操作来设置轴:

 将matplotlib.ticker导入为mtick# 省略实际绘图代码ax.xaxis.set_major_formatter(mtick.PercentFormatter(5.0))

这将在 0% 到 100% 的范围内显示从 0 到 5 的值.格式化程序在概念上与@Ffisegydd所建议的相似,不同之处在于它可以考虑任何现有的滴答声.

PercentFormatter() 接受三个参数,maxdecimalssymbol.max 允许您设置与轴上 100% 对应的值(在您的示例中,5).

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

请注意,如果您只是绘制数据,此格式化程序将使用通常会生成的任何刻度.除了输出到刻度线的字符串外,它不会修改任何内容.

更新

PercentFormatter 在2.1.0版中被Matplotlib接受.

I have a line chart based on a simple list of numbers. By default the x-axis is just the an increment of 1 for each value plotted. I would like to be a percentage instead but can't figure out how. So instead of having an x-axis from 0 to 5, it would go from 0% to 100% (but keeping reasonably spaced tick marks. Code below. Thanks!

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid.axislines import Subplot

data=[8,12,15,17,18,18.5]
fig=plt.figure(1,(7,4))
ax=Subplot(fig,111)
fig.add_subplot(ax)
plt.plot(data)

解决方案

This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter class. With this class you can do as follows to set the axis:

import matplotlib.ticker as mtick

# Actual plotting code omitted

ax.xaxis.set_major_formatter(mtick.PercentFormatter(5.0))

This will display values from 0 to 5 on a scale of 0% to 100%. The formatter is similar in concept to what @Ffisegydd suggests doing except that it can take any arbitrary existing ticks into account.

PercentFormatter() accepts three arguments, max, decimals, and symbol. max allows you to set the value that corresponds to 100% on the axis (in your example, 5).

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.

Note that this formatter will use whatever ticks would normally be generated if you just plotted your data. It does not modify anything besides the strings that are output to the tick marks.

Update

PercentFormatter was accepted into Matplotlib in version 2.1.0.

这篇关于Pyplot:在x轴上使用百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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