根据图而不是imshow映射颜色栏 [英] Map a colorbar based on plot instead of imshow
问题描述
我正在尝试为下面的代码示例提供颜色条.
I'm trying to get a colorbar for the following minimal example of my code.
g1 = gridspec.GridSpec(1, 1)
f, ((ax0)) = plt.subplots(1, 1)
ax0 = subplot(g1[0])
cmap = matplotlib.cm.get_cmap('viridis')
for i in linspace(0,1,11):
x = [-1,0,1]
y = [i,i,i]
rgba = cmap(i)
im = ax0.plot(x,y,color=rgba)
f.colorbar(im)
我还尝试了 f.colorbar(cmap)
可能很明显,但出现诸如
Probably pretty obvious, but I get errors such as
'ListedColormap' object has no attribute 'autoscale_None'
实际上,定义i的值更复杂,但是我认为这应该可以解决问题.我的数据是用plot绘制的,而不是用imshow绘制的(我知道如何制作颜色图).
In reality, the value defining i is more complex, but I think this should do the trick. My data is plotted with plot and not with imshow (for which I know how to make the colormap).
推荐答案
到目前为止,答案似乎过于复杂. fig.colorbar()
需要一个 ScalarMappable
作为其第一个参数.通常, ScalarMappable
是由 imshow
或 contour
图生成的,并且随时可用.
The answers so far seem overly complicated. fig.colorbar()
expects a ScalarMappable
as its first argument. Often ScalarMappable
s are produced by imshow
or contour
plots and are readily avaible.
在这种情况下,您需要定义自定义的 ScalarMappable
以提供给颜色栏.
In this case you would need to define your custom ScalarMappable
to provide to the colorbar.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
cmap = plt.cm.get_cmap('viridis')
for i in np.linspace(0,1,11):
x = [-1,0,1]
y = [i,i,i]
rgba = cmap(i)
im = ax.plot(x,y,color=rgba)
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
fig.colorbar(sm)
plt.show()
这篇关于根据图而不是imshow映射颜色栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!