Change color of selected matplotlib histogram bin bar, given it#39;s value(更改所选matplotlib直方图箱栏的颜色,给定值)
本文介绍了更改所选matplotlib直方图箱栏的颜色,给定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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变量自动将值所在的直方图上的条形图颜色更改为蓝色,例如:
如何实现此目标?
推荐答案
使用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()
退货:
这篇关于更改所选matplotlib直方图箱栏的颜色,给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:更改所选matplotlib直方图箱栏的颜色,给定值
基础教程推荐
猜你喜欢
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
