简体   繁体   English

用于散点图的 matplotlib 颜色条

[英]matplotlib colorbar for scatter

I'm working with data that has the data has 3 plotting parameters: x,y,c.我正在处理具有 3 个绘图参数的数据:x、y、c。 How do you create a custom color value for a scatter plot?如何为散点图创建自定义颜色值?

Extending this example I'm trying to do:扩展我正在尝试做的这个例子

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

but the result is TypeError: You must first set_array for mappable但结果是TypeError: You must first set_array for mappable

From the matplotlib docs on scatter 1 :来自 scatter 1上的 matplotlib 文档:

cmap is only used if c is an array of floats cmap 仅在 c 是浮点数组时使用

So colorlist needs to be a list of floats rather than a list of tuples as you have it now.所以 colorlist 需要是一个浮点数列表,而不是你现在拥有的元组列表。 plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. plt.colorbar() 需要一个可映射的对象,例如 plt.scatter() 返回的 CircleCollection。 vmin and vmax can then control the limits of your colorbar.然后 vmin 和 vmax 可以控制颜色条的限制。 Things outside vmin/vmax get the colors of the endpoints. vmin/vmax 之外的事物获得端点的颜色。

How does this work for you?这对你有什么作用?

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

图像示例

Here is the OOP way of adding a colorbar:这是添加颜色条的 OOP 方式

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.如果您希望通过两个变量分散并通过第三个变量分散颜色, Altair可能是一个不错的选择。

Creating the dataset创建数据集

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

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot牵牛星图

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Plot阴谋

在此处输入图片说明

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

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