简体   繁体   English

如何使用matplotlib的set_cmap()?

[英]how to use matplotlib's set_cmap()?

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, ie the colours are the same as in the standard palette ( http://i.stack.imgur.com/FjXoO.png ) 我想在我的绘图中尝试不同的色彩映射,但命令plt.set_cmap('hot')不起作用,即颜色与标准调色板中的颜色相同( http://i.stack.imgur.com/ FjXoO.png

I am using WXAgg backend under Debian Linux and matplotlib from Enthought's Canopy. 我在Debian Linux下使用WXAgg后端,在Enthought的Canopy中使用matplotlib。 I tried the Qt4Agg backend and the result was the same. 我尝试了Qt4Agg后端,结果是一样的。 How to properly change the colours? 如何正确改变颜色?

plt.set_cmap will set a colormap to be used, for example, in an image plot. plt.set_cmap将设置要使用的plt.set_cmap colormap ,例如,在图像绘图中。 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绘图时,您可以提供color关键字参数,该参数将选择线条的颜色,如下所示。

# ... 
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. 或者,您可以使用ax.set_color_cycle()设置新的颜色循环,它允许您选择颜色在添加新绘图时的更改方式,并有效地创建与以前相同的图形。 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> . matplotlib.pyplot.cm.<your_colormap_here>映射本身由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. 通过在0和1之间传递10个等间距的数字作为参数,您可以得到10个等间距的颜色。

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

示例图

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

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