【问题标题】:Advanced horizontal bar chart with Python?使用 Python 的高级水平条形图?
【发布时间】:2020-09-11 08:53:11
【问题描述】:

我想制作一个如下图所示的图表。 我怎样才能用python实现呢?很抱歉,我无法提供任何实现,因为我根本没有任何想法。我认为我的问题与此不同。

https://matplotlib.org/gallery/lines_bars_and_markers/barh.html#sphx-glr-gallery-lines-bars-and-markers-barh-py

有人可以用一些简单的数字给我一些建议吗?

【问题讨论】:

    标签: python matplotlib data-visualization


    【解决方案1】:

    tutorial for vertical gradient bars可以适配画出中间最黑点的水平条:

    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    import matplotlib.colors as mcolors
    import numpy as np
    
    def hor_gradient_image(ax, extent, darkest, **kwargs):
        '''
        puts a horizontal gradient in the rectangle defined by extent (x0, x1, y0, y1)
        darkest is a number between 0 (left) and 1 (right) setting the spot where the gradient will be darkest
        '''
        ax = ax or plt.gca()
        img = np.interp(np.linspace(0, 1, 100), [0, darkest, 1], [0, 1, 0]).reshape(1, -1)
        return ax.imshow(img, extent=extent, interpolation='bilinear', vmin=0, vmax=1, **kwargs)
    
    def gradient_hbar(y, x0, x1, ax=None, height=0.8, darkest=0.5, cmap=plt.cm.PuBu):
        hor_gradient_image(ax, extent=(x0, x1, y - height / 2, y + height / 2), cmap=cmap, darkest=darkest)
        rect = mpatches.Rectangle((x0, y - height / 2), x1 - x0, height, edgecolor='black', facecolor='none')
        ax.add_patch(rect)
    
    # cmap = mcolors.LinearSegmentedColormap.from_list('turq', ['paleturquoise', 'darkturquoise'])
    cmap = mcolors.LinearSegmentedColormap.from_list('turq', ['#ACFAFA', '#3C9E9E'])
    fig, ax = plt.subplots()
    for y in range(1, 11):
        x0, x1 = np.sort(np.random.uniform(1, 9, 2))
        gradient_hbar(y, x0, x1, ax=ax, height=0.7, darkest=0.5, cmap=cmap)
    ax.set_aspect('auto')
    ax.use_sticky_edges = False
    ax.autoscale(enable=True, tight=False)
    ax.grid(axis='x')
    plt.show()
    

    【讨论】:

    • 非常感谢!此外,我们可以将 x 轴更改为 log-scale 并在这些条旁边添加一些标签吗?
    • 我试过 plt.semilogx 并且它适用于轴转换。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 2023-03-29
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多