8
import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-np.pi,np.pi,101)
y=np.sin(x)+np.sin(3*x)/3
y1=np.sin(x)+np.sin(2*x)/3
y2=np.sin(x)+np.sin(3*x)/2

plt.set_cmap('hot')

plt.plot(x,y)
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()

I wanted to try a different colormap in my plot, but the command plt.set_cmap('hot') does not work, i.e. the colours are the same as in the standard palette ( https://i.sstatic.net/FjXoO.png)

I am using WXAgg backend under Debian Linux and matplotlib from Enthought's Canopy. I tried the Qt4Agg backend and the result was the same. How to properly change the colours?

1 Answer 1

11

plt.set_cmap will set a colormap to be used, for example, in an image plot. As you're simply plotting lines, it won't affect your plots.

When plotting using plt.plot you can provide a color keyword argument which will choose the color of your lines, as below.

# ... 
plt.plot(x,y, color='black')
plt.plot(x,y1, color='pink')
plt.plot(x,y2, color='green')
plt.show()

Alternatively, you could set a new color cycle using the ax.set_color_cycle(), which allows you to choose how the colors will change as you add new plots and effectively creates the same graph as before. See here for a demo.

# ...    
plt.gca().set_color_cycle(['black', 'pink', 'green'])

plt.plot(x,y)
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()

Finally, if you want to get a list of colors from an existing colormap then you can use the below code to get them spaced out linearly. The colormap itself is given by matplotlib.pyplot.cm.<your_colormap_here>. And by passing 10 equally spaced numbers between 0 and 1 as an argument, you get 10 equally spaced colors.

import numpy as np
import matplotlib.pyplot as plt

x=np.linspace(-np.pi,np.pi,101)
y=np.sin(x)+np.sin(3*x)/3
y1=np.sin(x)+np.sin(2*x)/3
y2=np.sin(x)+np.sin(3*x)/2

colors = plt.cm.hot(np.linspace(0,1,10))
plt.gca().set_color_cycle(colors)

plt.plot(x,y)
plt.plot(x,y1)
plt.plot(x,y2)
plt.show()

Example plot

Sign up to request clarification or add additional context in comments.

1 Comment

set_color_cycle is now deprecated. You can use from cycler import cycler and plt.gca().set_prop_cycle(cycler('color', colors)) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.