how to change the color of a single bar if condition is True matplotlib

前端 未结 2 1626
甜味超标
甜味超标 2020-11-30 03:45

I\'ve been googleing to find if it\'s possible to change only the color of a bar in a graph made by matplotlib. Imagine this graph:

相关标签:
2条回答
  • 2020-11-30 03:53

    for seaborn you can do something like this:

    values = np.array([2,5,3,6,4,7,1])   
    idx = np.array(list('abcdefg')) 
    clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
    sb.barplot(x=idx, y=values, palette=clrs) # color=clrs)
    

    for matplotlib:

    values = np.array([2,5,3,6,4,7,1])   
    idx = np.array(list('abcdefg')) 
    clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
    plt.bar(idx, values, color=clrs, width=0.4)
    plt.show()
    
    0 讨论(0)
  • 2020-11-30 04:15

    You need to use color instead of facecolor. You can also specify color as a list instead of a scalar value. So for your example, you could have color=['r','b','b','b','b']

    For example,

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    
    N = 5
    ind = np.arange(N)
    width = 0.5
    vals = [1,2,3,4,5]
    colors = ['r','b','b','b','b']
    ax.barh(ind, vals, width, color=colors)
    
    plt.show()
    

    is a full example showing you what you want.

    To answer your comment:

    colors = []
    for value in dictionary.keys(): # keys are the names of the boys
        if winner == value:
            colors.append('r')
        else:
            colors.append('b')
    
    bar(ind,num,width,color=colors)
    
    0 讨论(0)
提交回复
热议问题