Matplotlib: y轴显示百分数

2020-03-07  本文已影响0人  wzNote

运行以下代码,y轴的示数均为小数

import numpy as np
import matplotlib.pyplot as plt
 
y1 = np.array([0.21, 0.59, 0.6, 0.51, 0.29, 0.77, 0.86, 0.3680, 0.4550, 0.5650])
x = np.arange(2009,2019)
 
fig, ax1 = plt.subplots() 
ax1.plot(x, y1, color='c')

plt.savefig('xx.png', dpi=300)
plt.show()
效果展示
改为百分比显示
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker 

y1 = np.array([0.21, 0.59, 0.6, 0.51, 0.29, 0.77, 0.86, 0.3680, 0.4550, 0.5650])
x = np.arange(2009,2019)
 
fig, ax1 = plt.subplots() 
ax1.plot(x, y1, color='c')

# 添加此段代码即可
def to_percent(temp, position):
    return '%1.0f'%(10*temp) + '%'
plt.gca().yaxis.set_major_formatter(ticker.FuncFormatter(to_percent))

plt.savefig('xx.png', dpi=300)
plt.show()
效果展示
上一篇下一篇

猜你喜欢

热点阅读