Ylabel重新缩放范围,以0%结尾

时间:2019-07-05 13:48:47

标签: python matplotlib axis-labels

import numpy as np
import matplotlib.pyplot as plt

n = 1000

x = np.arange(0, n)
y1 = np.random.normal(50, 4, n)
y2 = np.random.normal(25, 2.5, n)
y3 = np.random.normal(10, 1.1, n)

fig, (ax1, ax2, ax3) = plt.subplots(nrows = 3, ncols = 1)
ax1.plot(x, y1, 'royalblue')
ax1.set(xticks = [], title = 'Title')
ax2.plot(x, y2, 'darkorange')
ax2.set(xticks = [])
ax3.plot(x, y3, 'forestgreen')
ax3.set(xlabel = 'Random sample')
fig.legend(['First', 'Second', 'Third'])

plt.show()

我希望ylabels以百分比显示,从0%开始并降低。例如,蓝色的应该从[30, 40, 50, 60, 70][-57.1%, -42.9%, -28.6%, -14.3%, 0%]。黄色的应该从[10, 20, 30, 40][-75%, -50%, -25%, 0%],绿色的应该从[5, 7.5, 10, 12.5, 15][-66.6%, -50%, -33.3%, -16.7%, 0%]

其余图表应该看起来完全一样,只有ylabels应该改变。

enter image description here

1 个答案:

答案 0 :(得分:1)

只需将当前的yticks转换为float,然后更改为您希望它们显示的范围,即可显示:

import numpy as np

ticks = [float(x) for x in yvals]
ticks = np.array(ticks) - max(ticks)
yticklabels = ['{0:.1%}'.format(x) for x in ticks]

分别为每个图执行此操作。