【问题标题】:How to create a bar plot with long horizontal error bars?如何创建带有长水平误差线的条形图?
【发布时间】:2020-03-15 06:57:24
【问题描述】:

我想模拟给定图像中的蓝色背景线。有人可以告诉我如何使用 Matplotlib 做到这一点吗?

基本上,它是this 的简单版本。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    这是一种使用拉伸的一维图像绘制条带的方法。图像得到一个范围以填充整个宽度和所需的高度。颜色映射的vmax 设置得高一点,以避免颜色太浅,与白色背景太相似。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # create some test data
    N = 40
    x = np.linspace(-3, 3, N)
    values = np.random.normal(0, 2, N)
    
    error_bands = np.array([2, 1, 0, 0, 1, 2])
    plt.imshow(error_bands.reshape(-1, 1), extent=[-10, 10, -3, 3], origin='lower',
               cmap='Blues_r', vmin=error_bands.min(), vmax=error_bands.max() * 1.4, alpha=0.3)
    
    plt.axhline(0, color='blueviolet', lw=3) # horizontal line at x=0
    
    plt.bar(x, values, width=(x[1] - x[0]) * 0.8, bottom=0, color='blueviolet')
    
    plt.gca().set_aspect('auto')  # removed the fixed aspect ratio forced by imshow
    plt.xlim(x[0] - 0.3, x[-1] + 0.3) # explicitly set the xlims, shorter than the extent of imshow
    
    plt.show()
    

    PS:一种更简单的方法,将 imshow 替换为对 axhspan 的一些调用,使用小 alpha 绘制水平条:

    for i in range(1, 4):
        plt.axhspan(-i, i, color='b', alpha=0.1)
    

    【讨论】:

    • 如果这回答了你的问题,你可以考虑投票和/或accepting答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多