Search code examples
pythonpandasmatplotlibhistogram

Change color of selected histogram bin bar, given it's value


Similar to a question I asked previously, I have a MWE like this:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

pd.Series(np.random.normal(0, 100, 1000)).plot(kind='hist', bins=50, color='orange')

bar_value_to_colour = 102

I then want to use the bar_value_to_colour variable to automatically change the colour of the bar on the histogram in which the value resides to blue, for example:

enter image description here

How can I achieve this?


Solution

  • It's easy to get the x coordinate of the bar with rectangle.get_x() but the problem is that the bars aren't plotted exactly at the specific values so I've had to choose the closest one. Here is my solution:

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    
    s = pd.Series(np.random.normal(0, 100, 10000))
    p = s.plot(kind='hist', bins=50, color='orange')
    
    bar_value_to_label = 100
    min_distance = float("inf")  # initialize min_distance with infinity
    index_of_bar_to_label = 0
    for i, rectangle in enumerate(p.patches):  # iterate over every bar
        tmp = abs(  # tmp = distance from middle of the bar to bar_value_to_label
            (rectangle.get_x() +
                (rectangle.get_width() * (1 / 2))) - bar_value_to_label)
        if tmp < min_distance:  # we are searching for the bar with x cordinate
                                # closest to bar_value_to_label
            min_distance = tmp
            index_of_bar_to_label = i
    p.patches[index_of_bar_to_label].set_color('b')
    
    plt.show()
    

    returns:

    enter image description here