用于分散的 matplotlib 颜色条 [英] matplotlib colorbar for scatter

查看:50
本文介绍了用于分散的 matplotlib 颜色条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理具有 3 个绘图参数的数据:x、y、c.如何为散点图创建自定义颜色值?

I'm working with data that has the data has 3 plotting parameters: x,y,c. How do you create a custom color value for a scatter plot?

扩展这个示例我正在尝试:

import matplotlib
import matplotlib.pyplot as plt
cm = matplotlib.cm.get_cmap('RdYlBu')
colors=[cm(1.*i/20) for i in range(20)]
xy = range(20)
plt.subplot(111)
colorlist=[colors[x/2] for x in xy] #actually some other non-linear relationship
plt.scatter(xy, xy, c=colorlist, s=35, vmin=0, vmax=20)
plt.colorbar()
plt.show()

但结果是TypeError: You must first set_array for mappable

推荐答案

来自 matplotlib docs on scatter 1:

From the matplotlib docs on scatter 1:

cmap 仅在 c 是浮点数组时使用

cmap is only used if c is an array of floats

所以 colorlist 需要是一个浮点数列表,而不是你现在拥有的元组列表.plt.colorbar() 需要一个可映射的对象,例如 plt.scatter() 返回的 CircleCollection.然后 vmin 和 vmax 可以控制颜色条的限制.vmin/vmax 之外的事物获得端点的颜色.

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

这对您有什么作用?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

这篇关于用于分散的 matplotlib 颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆