matplotlib colorbar for scatter

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?

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

218240 次浏览

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. Color bar ()需要一个可映射的对象,比如 plt.scatter ()返回的 CircleCollection。 然后,vmin 和 vmax 可以控制色彩条的限制。在 vmin/vmax 之外的东西会得到端点的颜色。

你觉得怎么样?

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

Image Example

If you're looking to scatter by two variables and color by the third, 牛郎星 can be a great choice.

创建数据集

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'])

牵牛星阴谋

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

阴谋

enter image description here

下面是添加色彩条的 the OOP way:

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