pyplot/matplotlib Bar chart with fill color depending on value

后端 未结 2 564
南笙
南笙 2021-02-01 22:31

I want to produce in python with matplotlib/pyplot

  • a bar chart with a fill depending on the value.
  • legend color bar

while

相关标签:
2条回答
  • 2021-02-01 23:09

    You can use Normalize and ScalarMappable without plotting a scatter. For example:

    import matplotlib mpl
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    f,(ax1,ax2) = plt.subplots(2)
    
    #ax1 --> plot here your bar chart
    
    norm = mpl.colors.Normalize(vmin=0, vmax=1)
    
    mpl.colorbar.ColorbarBase(ax2, cmap=cm.RdBu,
                                    norm=norm,
                                    orientation='horizontal')
    

    Finally, add the desired format to the colorbar.

    0 讨论(0)
  • 2021-02-01 23:16

    I couldn't figure out how to get the colorbar to work without plotting something else and then clearing it, so it's not the most elegant solution.

    import matplotlib.pyplot as plt
    from matplotlib import cm
    import numpy as np
    
    y = np.array([1, 4, 3, 2, 7, 11])
    colors = cm.hsv(y / float(max(y)))
    plot = plt.scatter(y, y, c = y, cmap = 'hsv')
    plt.clf()
    plt.colorbar(plot)
    plt.bar(range(len(y)), y, color = colors)
    plt.show()
    

    Bar chart with color bar

    0 讨论(0)
提交回复
热议问题