Change the color of specific bar on the histogram
Change the color of the specific bar on the histogram
import pandas as pd import matplotlib.pyplot as plt s = pd.Series([12, 15, 13, 20, 19, 20, 11, 19, 11, 12, 19, 13, 12, 10, 6, 19, 3, 1, 1, 0, 4, 4, 6, 5, 3, 7, 12, 7, 9, 8, 12, 11, 11, 18, 19, 18, 19, 3, 6, 5, 6, 9, 11, 10, 14, 14, 16, 17, 17, 19, 0, 2, 0, 3, 1, 4, 6, 6, 8, 7, 7, 6, 7, 11, 11, 10, 11, 10, 13, 13, 15, 18, 20, 19, 1, 10, 8, 16, 19, 19, 17, 16, 11, 1, 10, 13, 15, 3, 8, 6, 9, 10, 15, 19, 2, 4, 5, 6, 9, 11, 10, 9, 10, 9, 15, 16, 18, 13]) p = s.plot(kind='hist', bins=50, color='orange') bar_value_to_label = 5 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()
The following is the output that will be obtained:
2018-10-31T11:02:25+05:30
2018-10-31T11:02:25+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution