【问题标题】:Drawing a colorbar aside a line plot, using Matplotlib使用 Matplotlib 在线图旁边绘制颜色条
【发布时间】:2014-10-24 10:10:32
【问题描述】:

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

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

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

我见过几个示例,您将所有数据绘制为一个数组,并使用自动颜色条,但这里我将数据一一绘制(通过使用函数选择相关数据)。

编辑:

function(x,y,concentration,temperature,1,37,colors[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

【问题讨论】:

  • 我假设function 最终会调用“绘图”函数或类似函数。在那里你需要传递你的颜色。可以发function的内容吗?
  • 您不能删除问题中对ys 的引用吗?还是第一个框中的ys 变成第二个框中的y
  • 我对你的问题的理解:(1)你反复绘制一条曲线,其形状和颜色取决于一个参数,它是单调变化的; (2) 之后,您想使用 pl.colorbar 提示不同曲线的参数值。如果我是正确的,这很难做到,因为颜色条旨在与 pl.imshow 和 pl.countourf 而非 pl.plot 一起使用。也就是说,您应该能够使用两个子图,第一个子图是您的图,第二个子图是自己绘制的颜色条,正如 matplotlib.org/examples/api/colorbar_only.html 中所解释/举例说明的那样
  • 感谢您的链接,只是我不明白该示例是如何工作的。在发布之前我已经看过这个例子,但我无法让它为我的目的工作。本例中的“cmap”是什么?它包含什么?什么是“规范”?
  • @KayJansen 这是一项复杂的任务,您要么在 SO 上找到一位好心的 matplotlib 专家(我不是,抱歉),要么您主要靠自己。此外,我对您没有在问题中提及您之前的研究这一事实感到有些惊讶,但这是您在 SO 中的第一个问题......如果您打算闲逛,您最好阅读一些关于 提出好的问题。乔

标签: python matplotlib colorbar


【解决方案1】:

在折线图旁边画一个颜色条

请将我的解决方案(我仅使用 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()

示例

致谢

A similar problem, about a scatter plot

更新 - 2021 年 4 月 14 日

  1. 使用最新版本的 Matplotlib,不再需要声明 s_m.set_array([])。另一方面,它没有害处。
  2. 在绘图时,可能想要使用(稍微)更明显的color=c_m(norm(parameter)) 来代替color=s_m.to_rgba(parameter)

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2019-05-25
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多