类似于我之前问过的一个问题 https://stackoverflow.com/questions/35780048/labelling-a-matplotlib-histogram-bin-with-an-arrow,我有一个像这样的 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
变量自动将直方图上值所在条形的颜色更改为蓝色,例如:
我怎样才能实现这个目标?
很容易得到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()
returns:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)