使用Matplotlib在线图旁边绘制颜色条 [英] Drawing a colorbar aside a line plot, using Matplotlib

查看:186
本文介绍了使用Matplotlib在线图旁边绘制颜色条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在图形中添加颜色条,但是我不知道它是如何工作的.问题是我通过以下方式制作了自己的颜色代码:

I'm trying to add a color bar in a graph, but I don't understand how it works. The problem is that I make my own colorcode by:

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]将给我一种新的颜色.然后,我使用(自制)函数选择相关数据并相应地绘制它们.看起来像这样:

and colors[i] will give me a new color. Then I use (homemade) functions to select the relevant data and plot them accordingly. This would look something like this:

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

现在,我想在颜色栏中添加颜色,并带有可以更改的标签.我该怎么做?

Now I want to add the colors in a color bar, with labels I can change. How do I do this?

我看到了几个示例,其中将所有数据绘制为带有自动颜色条的一个数组,但是这里我通过使用函数选择相关数据来一张一张地绘制数据.

I have seen several examples where you plot all the data as one array, with automated color bars, but here I plot the data one by one (by using functions to select the relevant data).

function(x,y,concentration,temperature,1,37,colors [0])看起来像这样(简化):

function(x,y,concentration,temperature,1,37,colors[0]) looks like this (simplified):

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

推荐答案

在线条图旁边绘制颜色条

请将我的解决方案(我仅使用11个不同幅度的正弦)映射到您的问题(正如我告诉您的那样,从您在Q中写的内容很难理解).

Drawing a colorbar aside a line plot

Please map my solution (I used simply 11 sines of different amplitudes) to your problem (as I told you, it is difficult to understand from what you wrote in your 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()

示例

关于散点图的类似问题

这篇关于使用Matplotlib在线图旁边绘制颜色条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆