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
To change the color of a scatter point in matplotlib, there is the option "c" in the function scatter.
colorbar() in python. The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot indicating the color scale. Parameters: ax: This parameter is an optional parameter and it contains Axes or list of Axes.
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. 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.
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:
fig, ax = plt.subplots() im = ax.scatter(x, y, c=c) fig.colorbar(im, ax=ax)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With