pythonmatplotlibbar-chartcolormap

How do I colour my barchart based on a colourmap?


I want to change the color of the bars in the bar chart based on the colormap on the side. For each of the four bars, it should take value x (float between 0 and 1), find this on the colormap and color the bar accordingly. How would I tackle this? I found some threads that ask a similar question, but I can't get it to work. I'm working in Jupyter Notebook

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.cm import ScalarMappable
import ipywidgets as widgets
from ipywidgets import interact
import scipy.stats as st


def graph(#widgets#):
    ## Formats color bar.  Need the scalar mapable to enable use of the color bar.
    my_cmap = plt.cm.get_cmap('Reds')
    sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(vmin=0, vmax=1))
    cbar = plt.colorbar(sm)
    cbar.set_label('Probability')
    
    ## Test each bar against the range and determine probability of inclusion in range.
    for bar in s:
        ## find confidence interval max, min, and siee
        barmin = s - error_min
        barmax = s + error_max
        barsize = barmax - barmin
        ## Use the barmax/min and the selected range max/min to find the percentage of overlap.
        overlap = np.maximum(0, np.minimum(barmax, toprange) - np.maximum(barmin, bottomrange))
        length = barmax-barmin + toprange-bottomrange
        lengthx = barmax-barmin
        lengthy = toprange-bottomrange
 
        return 2*overlap/length, overlap/lengthx, overlap/lengthy
        
        average, x,y = overlap_percentage(x,y)

plt.show()

Bar chart that I'm trying to colour with the colourmap on the side:


Solution

  • Since you said you have values from 0 to 1 for each of the bars, you just need to pass those values through the colormap as the color argument in the bar plot function.

    import matplotlib.pyplot as plt
    import numpy as np
    
    N = 10
    x = np.arange(0, N)
    y = np.random.uniform(low=20, high=100, size=N)
    vals = np.random.random(N)
    
    my_cmap = plt.get_cmap('Reds')
    sm = plt.cm.ScalarMappable(cmap=my_cmap, norm=plt.Normalize(vmin=0, vmax=1))
    
    fig, ax = plt.subplots()
    p = ax.bar(x, y, color=my_cmap(vals))
    fig.colorbar(sm, ax=ax)
    fig.show()