Pyplot:在x轴上使用百分比

16

我有一个基于一组简单数字的折线图。默认情况下,x轴仅是每个值绘制的递增1。我希望它成为百分比,但不知道如何实现。因此,与其从0到5具有x轴,它将从0%到100%(但保持合理间隔的刻度线)。以下是代码。谢谢!

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)
3个回答

22
下面的代码将为您提供一个简化的基于百分比的x轴,它假设您的每个值都均匀地分布在0%和100%之间。它创建一个perc数组,其中包含可以用于绘图的均匀间隔的百分比。然后,使用matplotlib.ticker.FormatStrFormatter调整x轴的格式,以便包括百分号。不幸的是,这会使用旧的字符串格式化,而不是新格式,旧格式的文档可以在此处找到:here
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()

示例图


旧格式化样式没有任何问题。 它仍然是两种格式中更具互操作性的一种(例如,请参见日志记录模块)。 - Mad Physicist
1
如果原始值已经像0.5那样,事物会是什么格式?我想把它转换成50%。 - Dhruv Ghulati
1
另一个可能的解决方案是使用 mtick.FuncFormatter("{:.0%}".format),它使用新的样式格式化字符串,我认为更易读和灵活。 - Henry Hammond

18

虽然晚了几个月,但我已经在matplotlib中创建了PR#6251,以添加一个新的PercentFormatter类。使用这个类,您可以按照以下方式设置轴:

import matplotlib.ticker as mtick

# Actual plotting code omitted

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

这将在0%至100%的比例上显示从0到5的值。该格式化程序与@Ffisegydd建议执行的概念类似,只是它可以考虑任何任意现有的刻度。

PercentFormatter()接受三个参数:maxdecimalssymbolmax允许您设置对应于轴上100%的值(在您的示例中为5)。

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

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

更新

PercentFormatter已经在Matplotlib 2.1.0版中被接受。


2
完全晚了,但我写了这篇文章,希望它能有所帮助:
def transformColToPercents(x, rnd, navalue):
    
    # Returns a pandas series that can be put in a new dataframe column, where all values are scaled from 0-100%
    # rnd = round(x)
    # navalue = Nan== this
    
    hv = x.max(axis=0)
    lv = x.min(axis=0)
    
    pp = pd.Series(((x-lv)*100)/(hv-lv)).round(rnd)                        
    
    return pp.fillna(navalue)  


df['new column'] = transformColToPercents(df['a'], 2, 0)

将近7年前有点晚了.xD - chess_lover_6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接