Chr*_*ris 86 python plot matplotlib pandas
我有一个用pandas创建的现有情节,如下所示:
df['myvar'].plot(kind='bar')
Run Code Online (Sandbox Code Playgroud)
y轴的格式为float,我想将y轴更改为百分比.我找到的所有解决方案都使用ax.xyz语法,我只能将代码放在上面创建绘图的行下方(我不能将ax = 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()
Run Code Online (Sandbox Code Playgroud)
链接到上述解决方案:Pyplot:在x轴上使用百分比
Jia*_* Li 117
pandas dataframe plot将为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(['{:,.2%}'.format(x) for x in vals])
Run Code Online (Sandbox Code Playgroud)

erw*_*anp 69
Jianxun的解决方案为我完成了工作,但打破了窗口左下角的y值指示器.
我最终使用了FuncFormatter(并且还删除了这里建议的不必要的尾随零):
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)))
Run Code Online (Sandbox Code Playgroud)
一般来说,我建议使用FuncFormatter标签格式:它可靠,功能多样.
Mad*_*ist 64
这是几个月的晚了,但是我用matplotlib 创建了PR#6251来添加一个新PercentFormatter类.使用这个类,您只需要一行来重新格式化您的轴(如果计算导入的话,则需要两行matplotlib.ticker):
import ...
import matplotlib.ticker as mtick
ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
Run Code Online (Sandbox Code Playgroud)
PercentFormatter()接受三个参数,xmax,decimals,symbol.xmax允许您设置轴上对应于100%的值.如果您有0.0到1.0的数据并且想要将其显示在0%到100%之间,这很好.做吧PercentFormatter(1.0).
另外两个参数允许您设置小数点和符号后面的位数.它们分别默认为None和'%'.decimals=None将根据您显示的轴数自动设置小数点数.
np8*_*np8 27
对于那些正在寻找快速单线的人:
plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()])
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用Latex作为轴文本格式化程序,则必须添加一个反斜杠'\'
plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()])
Run Code Online (Sandbox Code Playgroud)
小智 12
我迟到了,但我才意识到这一点:对于那些不使用轴而只是子图的人,ax可以替换plt.gca()为。
回应@Mad Physicist 的回答,使用该包PercentFormatter将是:
import matplotlib.ticker as mtick
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(1))
#if you already have ticks in the 0 to 1 range. Otherwise see their answer
Run Code Online (Sandbox Code Playgroud)
我提出了一种替代方法seaborn
工作代码:
import pandas as pd
import seaborn as sns
data=np.random.rand(10,2)*100
df = pd.DataFrame(data, columns=['A', 'B'])
ax= sns.lineplot(data=df, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='title')
#changing ylables ticks
y_value=['{:,.2f}'.format(x) + '%' for x in ax.get_yticks()]
ax.set_yticklabels(y_value)
Run Code Online (Sandbox Code Playgroud)
您可以在一行中完成此操作,而无需导入任何内容:
plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{}%'.format))
如果你想要整数百分比,你可以这样做:
plt.gca().yaxis.set_major_formatter(plt.FuncFormatter('{:.0f}%'.format))
您可以使用ax.yaxis或plt.gca().yaxis。FuncFormatter仍然是 的一部分matplotlib.ticker,但您也可以plt.FuncFormatter作为快捷方式执行。
| 归档时间: |
|
| 查看次数: |
89901 次 |
| 最近记录: |