Matplotlib:将颜色栏添加到不可映射的对象 [英] Matplotlib: Add colorbar to non-mappable object

查看:163
本文介绍了Matplotlib:将颜色栏添加到不可映射的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列的行代表变量的变化;每个都有独特的颜色.因此,我想在绘图旁边添加一个颜色条.所需的输出如下所示.

I have a series of lines representing the change of a variable; each with a unique color. For that reason I want to add a colorbar next to the plot. The desired output is shown below.

问题在于plot是不可映射的对象,即必须手动添加颜色栏.我认为我当前的解决方案(如下)不是最优的,因为它涉及到大小参数,而我对此无心控制.我希望使用与可映射对象相似的解决方案(例如当前解决方案下方的示例).

The problem is that plot is a non-mappable object, i.e. the colorbar has to be added manually. I consider my current solution (below) sub-optimal as it involves size parameters of which I have no interest in controlling. I'd prefer a similar solution as for a mappable object (example below current solution).

import numpy             as np
import matplotlib        as mpl
import matplotlib.pyplot as plt

x    = np.linspace(0, 5, 100)
N    = 20
cmap = plt.get_cmap('jet',N)

fig  = plt.figure(figsize=(8,6))
ax1  = fig.add_axes([0.10,0.10,0.70,0.85])

for i,n in enumerate(np.linspace(0,2,N)):
    y = np.sin(x)*x**n
    ax1.plot(x,y,c=cmap(i))

plt.xlabel('x')
plt.ylabel('y')

ax2  = fig.add_axes([0.85,0.10,0.05,0.85])
norm = mpl.colors.Normalize(vmin=0,vmax=2)
cb1  = mpl.colorbar.ColorbarBase(ax2,cmap=cmap,norm=norm,orientation='vertical')

plt.show()

所需解决方案

(显然是替换imshow)

fig,ax = plt.subplots()
cax    = ax.imshow(..)
cbar   = fig.colorbar(cax,aspect=10)
plt.show()

推荐答案

您可以定义自己的ScalarMappable并像在情节中一样使用它.
(请注意,我将numbero f颜色更改为21,以具有很好的0.1间距)

You may define your own ScalarMappable and use it just as if it was present in the plot.
(Note that I changed the numbero f colors to 21 to have nice spacings of 0.1)

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

x = np.linspace(0, 5, 100)
N = 21
cmap = plt.get_cmap('jet',N)

fig = plt.figure(figsize=(8,6))
ax1 = fig.add_axes([0.10,0.10,0.70,0.85])

for i,n in enumerate(np.linspace(0,2,N)):
    y = np.sin(x)*x**n
    ax1.plot(x,y,c=cmap(i))

plt.xlabel('x')
plt.ylabel('y')

norm = mpl.colors.Normalize(vmin=0,vmax=2)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0,2,N), 
             boundaries=np.arange(-0.05,2.1,.1))


plt.show()

这篇关于Matplotlib:将颜色栏添加到不可映射的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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