【发布时间】:2021-07-19 00:47:57
【问题描述】:
我正在尝试在绘图中使用 LineCollection 绘制一些线条。这些线中的每一条都需要映射到颜色条,其范围因每条线而异。我按照这里的解释试过了
最后,我想要一个颜色条,比如说三行,覆盖所有范围。但是,颜色条是为最后一行值设置的。所以我看这里
https://matplotlib.org/stable/gallery/images_contours_and_fields/multi_image.html
但我并不成功,因为我对 Matplotlib 还很陌生。我在下面粘贴我的代码。我只是想在颜色栏中为所有三条线映射线的值(也显示在 y 轴上)。任何帮助表示赞赏。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import colors
lineSegments = [np.linspace(0,1,10),
np.linspace(0,5,10),
np.linspace(0,2,10)]
xVec = np.linspace(0,1,10)
fig, ax = plt.subplots()
for i in range(0, len(lineSegments)):
cValue = np.linspace( min(lineSegments[i]), max(lineSegments[i]) )
norm = colors.Normalize(vmin=cValue.min(), vmax=cValue.max() )
Points = np.array([xVec, lineSegments[i]]).T.reshape(-1,1,2)
PointSegments = np.concatenate([Points[:-1],Points[1:]], axis=1)
lc = LineCollection(PointSegments, cmap=plt.get_cmap('jet'),
norm=norm)
#plt.gca().add_collection(lc)
ax.add_collection(lc)
ax.set_xlim( min(xVec), max(xVec) )
ax.set_ylim( np.amin(lineSegments), np.amax(lineSegments) )
lc.set_array(cValue)
fig.colorbar(lc)
def update(changed_lines):
for i in range(0, len(lineSegments)):
if (changed_lines.get_cmap() != lc.get_cmap()
or changed_lines.get_clim() != lc.get_clim()):
lc.set_cmap(changed_lines.get_cmap())
lc.set_clim(changed_lines.get_clim())
for i in range(0, len(lineSegments)):
lc.callbacksSM.connect('changed',update)
plt.show()
【问题讨论】:
标签: numpy matplotlib matplotlib-basemap