根据它的值,更改所选matplotlib直方图bin bar的颜色

时间:2016-03-09 11:46:34

标签: python matplotlib plot bar-chart

Similar to a question I asked previously,我有一个像这样的MWE:

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

然后,我想使用bar_value_to_colour变量自动更改值所在的直方图上条形图的颜色为蓝色,例如:

enter image description here

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:8)

使用x很容易获得条形的rectangle.get_x()坐标,但问题是条形图并未精确地绘制在特定值上,所以我'必须选择最接近的一个。这是我的解决方案:

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()

返回:

enter image description here