对于颜色逐渐变化的多个图,显示matplotlib颜色条而不是图例 [英] show matplotlib colorbar instead of legend for multiple plots with gradually changing colors

查看:27
本文介绍了对于颜色逐渐变化的多个图,显示matplotlib颜色条而不是图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的图,该图以一定的顺序显示属于大型数据集的许多曲线,比方说图1..n.曲线的形状随着n的增加而逐渐变化.读者可以准确地知道哪个图属于n的哪个值并不重要,但读者应该能够猜测n的量级.

I am trying to make a simple plot that shows a lot of curves that belong to a large dataset with a certain order, let's say plot 1..n. The shape of the curves changes gradually with increasing n. It is not important that readers can see exactly which plot belongs to which value of n, but they should be able to guess in which order of magnitude n is.

因此,我这样做:

nValues = range(0,30)
xValues = np.linspace(0,10)
dataset = [(xValues-5-0.5*n)**2 for n in nValues]
colors = {n: colorsys.hsv_to_rgb(hue,0.9,0.7) for n,hue in zip(nValues,np.linspace(0,0.7,len(nValues)))}
for n in nValues:
    plt.plot(dataset[n],color=colors[n])

(请注意,这只是示例,我的数据实际上存储在一个不错的pandas数据框中.)

(Just to be clear, this is just for the example, my data is actually stored in a nice pandas dataframe.)

我想在图旁边添加一个色条,而不是一个图例,该色条上可能带有几个刻度线和标签(至少最小和最大),以指示哪种颜色属于n的哪个值,但是我不知道如何做到这一点.我认为,如果实际上从ColorMap中获取绘图颜色,事情可能会更容易,但是我也不知道该怎么做,也不知道如何从那里进行.

Instead of a legend, I would like to add a colorbar next to the plot with perhaps a couple of tickmarks and labels (at least the minimum and the maximum), to indicate which color belongs to which value of n, but I don't know how to accomplish this. I figured things might be easier if I actually get my plot colors from a ColorMap, but I also don't know how to do that and I also wouldn't know how to proceed from there.

欢迎任何指针!

推荐答案

@tom和@Joe Kington都是正确的:之前已经有人问过这个问题.但是,我尝试以较少的努力作为链接的答案来举例说明.要使用颜色图(始终将[0,1]中的值映射到颜色),首先需要对数据进行规范化.为此,您可以使用 Normalize 类. ScalarMappable 实例仅在您打算创建颜色条时才需要.

Both @tom and @Joe Kington are right: this has been asked before. However, I tried to make an example with slighty less efforts as the linked answers. To use a colormap (which always maps values from [0,1] to color), you first need to normalize your data. For that you can use the Normalize class. The ScalarMappable instance is only required if you intend to create a colorbar.

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.cm as cm
import numpy as np

# your dataset
nValues = np.arange(0,30)
xValues = np.linspace(0,10)
dataset = [(xValues-5-0.5*n)**2 for n in nValues]

# setup the normalization and the colormap
normalize = mcolors.Normalize(vmin=nValues.min(), vmax=nValues.max())
colormap = cm.jet

# plot
for n in nValues:
    plt.plot(dataset[n], color=colormap(normalize(n)))

# setup the colorbar
scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
scalarmappaple.set_array(nValues)
plt.colorbar(scalarmappaple)

# show the figure
plt.show()

结果:

这篇关于对于颜色逐渐变化的多个图,显示matplotlib颜色条而不是图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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