【问题标题】:Change color of selected matplotlib histogram bin bar, given it's value给定它的值,更改所选 matplotlib 直方图 bin 条的颜色
【发布时间】:2023-03-26 21:05:01
【问题描述】:

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 变量自动将值所在的直方图上的条形颜色更改为蓝色,例如:

我怎样才能做到这一点?

【问题讨论】:

  • 我不完全明白你想要达到什么目的。是否要将值为 100 的条的颜色更改为蓝色?你能试着解释一下你问题的最后一句话吗?
  • 我已经编辑了这个问题,这会让事情更清楚吗?

标签: python matplotlib plot bar-chart


【解决方案1】:

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

返回:

【讨论】:

  • @BML91 我在我的代码中做了一些小修正,所以它计算了到条形中间的距离,而不是从条形的左侧坐标计算距离。 tmp = abs((rectangle.get_x() + (rectangle.get_width() * (1 / 2))) - bar_value_to_label) 而不是 tmp = abs(rectangle.get_x() - bar_value_to_label)。条形是否更厚可能很重要..
【解决方案2】:

这是@Tony Barbarino 解决方案的更简单版本。它使用numpy.quantize 来避免显式迭代补丁边缘。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Allocate the bin edges ourselves, so we can quantize the bar
# value to label with np.digitize.
bins = np.linspace(-400, 400, 50)

# We want to change the color of the histogram bar that contains
# this value.
bar_value_to_label = 100

# Get the index of the histogram bar that contains that value.
patch_index = np.digitize([bar_value_to_label], bins)[0]

s = pd.Series(np.random.normal(0, 100, 10000))
p = s.plot(kind='hist', bins=bins, color='orange')

# That's it!
p.patches[patch_index].set_color('b')
plt.show()

这可以简单地推广到多个条形图。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Allocate the bin edges ourselves, so we can quantize the bar
# value to label with np.digitize.
bins = np.linspace(-400, 400, 50)

# We want to change the color of the histogram bar that contains
# these values.
bar_values_to_label = [-54.3, 0, 121]

# Get the indices of the histogram bar that contains those values.
patch_indices = np.digitize([bar_values_to_label], bins)[0]

s = pd.Series(np.random.normal(0, 100, 10000))
p = s.plot(kind='hist', bins=bins, color='orange')

for patch_index in patch_indices:
    # That's it!
    p.patches[patch_index].set_color('b')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 2021-12-25
    • 2022-08-15
    相关资源
    最近更新 更多