【问题标题】:Plotting variable axis ticks绘制可变轴刻度
【发布时间】:2020-03-29 11:22:29
【问题描述】:

您好,尝试根据计算最小值和最大值来制作变量 y(或 x)轴刻度。到目前为止,这是我尝试过的:

ymin = (round((min(ECG_Data)), 1))
ymax = (round((max(ECG_Data)), 1))
..
plt.ylim(ymin - 0.05, ymax + 0.05)
plt.yticks(np.arange(ymin - 0.1, ymax + 0.2, step = 0.1))

示例 1

最低值约为-0.38,最低值为-0.4,这很好。但最高值在 0.9 以上,滴答停在 0.9,这是我不想要的。

示例 2:

完美的示例,但正如您在上面的代码中所见,我在 ylim 和 yticks 中使用了硬编码的 - 和 + 值,这仅适用于这个特定的图表。

(如果我不在 plt.yticks 中使用数值,则上下刻度都丢失,例如示例 1 中缺少最高刻度)

如何使用可变刻度制作可变轴?每次取最小值和最大值来确定最低和最高刻度。

感谢您与我一起思考/帮助我!

【问题讨论】:

    标签: python python-3.x matplotlib plot


    【解决方案1】:

    那是因为np.arange 是半开区间。所以它不包括你想要的ymax。如果你想要一个封闭的区间,你可以试试

    np.linspace(start = ymin, stop = ymax, num = (ymax - ymin)/0.1)
    

    【讨论】:

    • 尝试后,上下刻度在数据较低/较高时停止(因此两者都丢失)
    • 可能是因为round。试试floorceil
    • 正在尝试,但它不带小数四舍五入。所以现在有刻度但是太多了哈哈因为刻度范围现在从 -1 到 +1
    • 感谢地板和天花板的提示!
    【解决方案2】:

    使这种情况稍微更具动态性的一种方法可能是根据数据的最小值和最大值计算yrange,然后基于此推导出yticks。比如

    from math import floor, ceil
    import numpy as np
    import matplotlib.pyplot as plt
    
    data = np.random.rand(100,)*1.5 - 0.4 # generate some toy data
    
    add_percent = 10
    round_to_decimal = 1 # n decimal places, e.g. 2 would mean round to 2nd dec place
    
    ymax, ymin = data.max(), data.min()
    offset = (abs(ymin)+abs(ymax))/2 * add_percent/100
    yrange = (floor((ymin - offset)*10**round_to_decimal)/10**round_to_decimal, 
              ceil((ymax + offset)*10**round_to_decimal)/10**round_to_decimal)
    
    STEP = 0.1 # step=.1 is a bit arbitrary, depends on your data
    yticks = np.arange(yrange[0], yrange[1]+STEP, step=STEP) 
    # same as: np.linspace(*yrange, num=np.ptp(yrange)/STEP+1)
    
    fig, ax1 = plt.subplots()
    ax1.plot(data)
    ax1.set_ylim(yrange)
    ax1.set_yticks(yticks)
    

    请注意,我添加了小数位的四舍五入并添加了yrange 的相对数量,以便看起来更好。结果与此类似:

    【讨论】:

    • @lanneke113:太好了!基本上,无论您使用np.arange 还是np.linspace,这只是为了获得正确的范围。其余的更像是化妆品,但有时它关于外观的;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多