【问题标题】:How to draw a horizontal percentage bar plot with matplotlib?如何使用 matplotlib 绘制水平百分比条形图?
【发布时间】:2019-03-12 11:03:58
【问题描述】:

是否可以使用我在下面附加的 matplotlib 绘制类似的图表?

【问题讨论】:

标签: python matplotlib bar-chart pie-chart


【解决方案1】:

使用barh 方法,类似于:

import matplotlib.pyplot as plt

never = [74]
seldom = [18]
undecided = [8]

y = [0]

plt.barh(y, never, color='#b5ffb9', edgecolor='white')
plt.barh(y, seldom, left=never, color='#f9bc86', edgecolor='white')
plt.barh(y, undecided, left=[100-i for i in undecided], color='#a3acff', edgecolor='white')

plt.show() 

输出:

【讨论】:

    【解决方案2】:

    发件人:https://matplotlib.org/gallery/lines_bars_and_markers/broken_barh.html

    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    
    fig, ax = plt.subplots()
    
    start = 0
    never = 54
    seldom = 43
    undecided = 3
    
    ax.broken_barh([(start, never), (never, never+seldom), (never+seldom, never+seldom+undecided)], [10, 9], facecolors=('#6259D8', '#E53F08', '#FDB200'))
    ax.set_ylim(5, 15)
    ax.set_xlim(0, 100)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_yticks([15, 25])
    ax.set_xticks([0, 25, 50, 75, 100])
    
    ax.set_axisbelow(True) 
    
    ax.set_yticklabels(['Q1'])
    ax.grid(axis='x')
    ax.text(never-6, 14.5, "54%", fontsize=8)
    ax.text((never+seldom)-6, 14.5, "43%", fontsize=8)
    ax.text((never+seldom+undecided)+2, 14.5, "3%", fontsize=8)
    
    fig.suptitle('This is title of the chart', fontsize=16)
    
    leg1 = mpatches.Patch(color='#6259D8', label='Never')
    leg2 = mpatches.Patch(color='#E53F08', label='Seldom')
    leg3 = mpatches.Patch(color='#FDB200', label='Undecided')
    ax.legend(handles=[leg1, leg2, leg3], ncol=3)
    
    plt.show()
    

    这是结果:

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多