更改选定直方图 bin 条的颜色(给定其值)

问题描述 投票:0回答:2

类似于我之前问的问题,我有一个像这样的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
变量自动将直方图上值所在的条形颜色更改为蓝色,例如:

我怎样才能实现这个目标?

python pandas matplotlib histogram
2个回答
10
投票

使用

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

返回:


3
投票

这是@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()

© www.soinside.com 2019 - 2024. All rights reserved.