Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of selected matplotlib 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?

like image 267
BML91 Avatar asked Mar 09 '16 11:03

BML91


People also ask

How do I assign a color in Matplotlib?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

Can we select Colours of the visualization using Matplotlib?

With matplotlibYou can pass plt. scatter a c argument, which allows you to select the colors.


1 Answers

Here's a simpler version of @Tony Barbarino's solution. It uses numpy.quantize to avoid iterating over the patch edges explicitly.

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

# Allocate the bin edges ourselves, so we can quantize the bar
# value to label with np.digitize.
bins = np.linspace(-400, 400, 50)

# We want to change the color of the histogram bar that contains
# this value.
bar_value_to_label = 100

# Get the index of the histogram bar that contains that value.
patch_index = np.digitize([bar_value_to_label], bins)[0]

s = pd.Series(np.random.normal(0, 100, 10000))
p = s.plot(kind='hist', bins=bins, color='orange')

# That's it!
p.patches[patch_index].set_color('b')
plt.show()

Color one histogram bar

This generalizes trivially to multiple bars.

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

# Allocate the bin edges ourselves, so we can quantize the bar
# value to label with np.digitize.
bins = np.linspace(-400, 400, 50)

# We want to change the color of the histogram bar that contains
# these values.
bar_values_to_label = [-54.3, 0, 121]

# Get the indices of the histogram bar that contains those values.
patch_indices = np.digitize([bar_values_to_label], bins)[0]

s = pd.Series(np.random.normal(0, 100, 10000))
p = s.plot(kind='hist', bins=bins, color='orange')

for patch_index in patch_indices:
    # That's it!
    p.patches[patch_index].set_color('b')
plt.show()

Color multiple histogram bars

like image 151
ndronen Avatar answered Nov 15 '22 17:11

ndronen