绘制后更改直方图颜色

1 投票
1 回答
893 浏览
提问于 2025-04-19 00:46

我怎么能在画完直方图之后改变它的颜色呢?(使用 hist 函数)

z = hist([1,2,3])
z.set_color(???) < -- Something like this

还有,我怎么能查看直方图的颜色是什么呢?

z = hist([1,2,3])
color = z.get_color(???) < -- also Something like this

谢谢你。

1 个回答

3

确实有这样的函数。你只需要保存hist返回的patches,然后访问每个patchfacecolor属性:

import matplotlib.pyplot as plt
n, bins, patches = plt.hist([1,2,3])
for p in patches:
    print p.get_facecolor()
    p.set_facecolor((1.0, 0.0, 0.0, 1.0))

输出:

(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)
(0.0, 0.5, 0.0, 1.0)

注意,每个区间(bin)会得到一个patch。默认情况下,hist会绘制10个区间。你可以通过plt.hist([1,2,3], bins=3)来定义不同的区间数量。

撰写回答