gpt4 book ai didi

python - 给定它的值,更改所选 matplotlib 直方图 bin 条的颜色

转载 作者:太空狗 更新时间:2023-10-29 20:58:15 24 4
gpt4 key购买 nike

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

我怎样才能做到这一点?

最佳答案

使用 rectangle.get_x() 很容易获得柱的 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

关于python - 给定它的值,更改所选 matplotlib 直方图 bin 条的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35890738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com