matplotlib 如何按比例缩放轴上的刻度

bxpogfeg  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(116)

y轴上的数字可能分布在一个很大的范围内,我想要的只是一个带有刻度[5,10,15,20,50,100,500,1000,1500,2000,2500]的轴,但要按比例分布。

import matplotlib.pyplot as plt
from datetime import datetime
x_axis = [datetime.strptime(date, "%d/%m/%y").date() for date in ['06/03/23', '13/03/23']]
y1 = [2400, 1900]
y2 = [1800, 1800]
y3 = [4, 3]
plt.plot(x_axis, y1, label="1")
plt.plot(x_axis, y2, label="2")
plt.plot(x_axis, y3, label="3")
plt.gcf().autofmt_xdate()
plt.xticks(x_axis)
plt.yticks([5,10,15,20,50,100,500,1000,1500,2000,2500])

vm0i2vca

vm0i2vca1#

我不认为有一个内置的解决方案,但你可以定义自己的规模作为一个连续的线性规模与FuncScale(我改变了你的刻度,使更容易计算,但我希望你得到的想法):

import matplotlib.pyplot as plt
from matplotlib.scale import FuncScale
from datetime import datetime

def scale_func(x):
    y = x.copy()
    for i, e in enumerate(x):
        if e > 500:
            y[i] = 55 + 0.01*e
        elif e > 100:
            y[i] = 35 + 0.05*e
        elif e > 20:
            y[i] = 15 + 0.25*e
    return y

def scale_func_inverse(x):
    y = x.copy()
    for i, e in enumerate(x):
        if e > 60:
            y[i] = 100*(e-55)
        elif e > 40:
            y[i] = 20*(e-35)
        elif e > 20:
            y[i] = 4*(e-15)
    return y

x_axis = [datetime.strptime(date, "%d/%m/%y").date() for date in ['06/03/23', '13/03/23']]
y1 = [2400, 1900]
y2 = [1800, 1800]
y3 = [4, 3]
fig, ax = plt.subplots()
plt.plot(x_axis, y1, label="1")
plt.plot(x_axis, y2, label="2")
plt.plot(x_axis, y3, label="3")

scale = FuncScale(ax, functions=(scale_func, scale_func_inverse))
ax.set_yscale(scale)

plt.gcf().autofmt_xdate()
plt.xticks(x_axis)
yticks = [5,10,15,20,40,60,80,100,200,300,400,500,1000,1500,2000,2500]
plt.yticks(yticks, yticks)
plt.show()

输出:

相关问题