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:
How can I achieve this?
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.
With matplotlibYou can pass plt. scatter a c argument, which allows you to select the colors.
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With