Python matplotlib custom colorbar for plotted lines with manually assigned colors

你说的曾经没有我的故事 提交于 2021-01-29 21:43:11

问题


I'm trying to define a colorbar for the following type of plot.

import matplotlib.pyplot as plt
import numpy as np

for i in np.arange(0,10,0.1):
    plt.plot(range(10),np.ones(10)*i,c=[i/10.,0.5,0.25])
plt.show()

This is just a simplified version of my actual data, but basically, I'd like a series of lines plotted and colored by another variable with a colorbar key. This is easy to do in scatter, but I can't get scatter to plot connected lines. Points are too clunky. I know this sounds like basic stuff, but I'm having a helluva time finding a simple solution ... what obvious solution am I missing?


回答1:


You can build a custom color map and a mappable from it, then pass to colorbar:

from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import matplotlib.colors as mcolors

color_list = [(i/10, 0.5,0.25) for i in np.arange(0,10,0.1)]
cmap = mcolors.LinearSegmentedColormap.from_list("my_colormap", color_list)
cmappable = ScalarMappable(norm=Normalize(0,10), cmap=cmap)

plt.figure(figsize=(10,10))
for j,i in enumerate(np.arange(0,10,0.1)):
    plt.plot(range(10),np.ones(10)*i,c=color_list[j])
    
plt.colorbar(cmappable)
plt.show()

Output:



来源:https://stackoverflow.com/questions/65618997/python-matplotlib-custom-colorbar-for-plotted-lines-with-manually-assigned-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!