Python matplotlib自定义颜色栏,用于使用手动分配的颜色绘制的线条 [英] Python matplotlib custom colorbar for plotted lines with manually assigned colors

查看:64
本文介绍了Python matplotlib自定义颜色栏,用于使用手动分配的颜色绘制的线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下类型的图定义一个颜色条.

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?

推荐答案

您可以构建自定义颜色映射和可映射的颜色映射,然后传递给 colorbar :

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()

输出:

这篇关于Python matplotlib自定义颜色栏,用于使用手动分配的颜色绘制的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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