简体   繁体   English

PatchCollection的Matplotlib colorbar会覆盖颜色

[英]Matplotlib colorbar for PatchCollection overrides colors

I am plotting patches according to values set in the variable values. 我正在根据变量值中设置的值绘制补丁。

pc = PatchCollection(patches, match_original=True)  

norm = Normalize()
cmap = plt.get_cmap('Blues')
pc.set_facecolor(cmap(norm(values)))
ax.add_collection(pc)

在此输入图像描述

Now i also want an additional colorbar. 现在我还想要一个额外的颜色条。 If i interject (eg before set_facecolor) 如果我插入(例如在set_facecolor之前)

pc.set_array(values) # values
plt.colorbar(pc)

在此输入图像描述

it works, but now all colors have turned to a greyscale. 它有效,但现在所有的颜色都变成了灰度。 The following set_facecolor does not change anything. 以下set_facecolor不会更改任何内容。 Even when i add a cmap= command in the plt.colorbar() everything remains in the greyscale. 即使我在plt.colorbar()添加cmap=命令,一切都仍然是灰度。 I have no clue what to do about it. 我不知道该怎么做。

Are you asking how to color a collection by a specific colormap? 您是否在询问如何通过特定的色彩图为集合着色?

Just set the colormap ( cmap ) as well as the array . 只需设置colormap( cmap )以及array

For example: 例如:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PatchCollection

num = 10
data = np.random.random((num, 2))
values = np.random.normal(10, 5, num)

# I'm too lazy to draw irregular polygons, so I'll use circles
circles = [plt.Circle([x, y], 0.1) for (x,y) in data]
col = PatchCollection(circles)

col.set(array=values, cmap='jet')

fig, ax = plt.subplots()

ax.add_collection(col)
ax.autoscale()
ax.axis('equal')

fig.colorbar(col)
plt.show()

在此输入图像描述

To explain what's going on in your question: 要解释你的问题中发生了什么:

For collections, the facecolors are either manually set (ie set_facecolors ) or they're colormapped to a range of values ( set_array ) controlled by a colorbar. 对于集合,可以手动设置set_facecolors颜色(即set_facecolors ),也可以将颜色映射到由颜色条控制的一系列值( set_array )。 These two options are mutually exclusive. 这两个选项是互斥的。 Therefore, after you call set_array , the original facecolors are ignored. 因此,在调用set_array ,将忽略原始的facecolors。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM