使用Matplotlib在线图上绘制颜色条

时间:2014-10-24 10:10:33

标签: python matplotlib colorbar

我试图在图表中添加一个颜色条,但我不明白它是如何工作的。问题是我通过以下方式制作了自己的颜色代码:

x = np.arange(11)

ys = [i+x+(i*x)**2 for i in range(11)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))

colors[i]会给我一种新的颜色。然后我使用(自制)函数来选择相关数据并相应地绘制它们。这看起来像这样:

function(x,y,concentration,temperature,1,37,colors[0])
function(x,y,concentration,temperature,2,37,colors[1])
# etc

现在我想在颜色条中添加颜色,我可以更改标签。我该怎么做?

我看过几个例子,你把所有数据都绘制成一个数组,带有自动颜色条,但是我在这里逐个绘制数据(通过使用函数来选择相关数据)。

编辑:

函数(x,y,浓度,温度,1,37,颜色[0])看起来像这样(简化):

def function(x,y,c,T,condition1,condition2,colors):

  import matplotlib.pyplot as plt

  i=0

  for element in c:
   if element == condition1:
      if T[i]==condition2:
          plt.plot(x,y,color=colors,linewidth=2)

  i=i+1

return

1 个答案:

答案 0 :(得分:9)

在线图

旁边绘制颜色条

请将我的解决方案(我只使用11种不同振幅的正弦值)映射到您的问题中(正如我告诉您的那样,很难理解您在Q中所写的内容)。

import matplotlib
import numpy as np
from matplotlib import pyplot as plt

# an array of parameters, each of our curves depend on a specific
# value of parameters
parameters = np.linspace(0,10,11)

# norm is a class which, when called, can normalize data into the
# [0.0, 1.0] interval.
norm = matplotlib.colors.Normalize(
    vmin=np.min(parameters),
    vmax=np.max(parameters))

# choose a colormap
c_m = matplotlib.cm.cool

# create a ScalarMappable and initialize a data structure
s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
s_m.set_array([])

# plotting 11 sines of varying amplitudes, the colors are chosen
# calling the ScalarMappable that was initialised with c_m and norm
x = np.linspace(0,np.pi,31)
for parameter in parameters:
    plt.plot(x,
             parameter*np.sin(x),
             color=s_m.to_rgba(parameter))

# having plotted the 11 curves we plot the colorbar, using again our
# ScalarMappable
plt.colorbar(s_m)

# That's all, folks
plt.show()

实施例

Curves+colormap

致谢

A similar problem, about a scatter plot