简体   繁体   English

如何将颜色条放入 matplotlib 图例中

[英]How to put a colorbar into a matplotlib legend

I have code which produces this figure:我有产生这个数字的代码: 在此处输入图像描述

In this plot, the color indicates the horizontal offset of the lower end of each line.在此图中,颜色表示每条线下端的水平偏移量。 I would like a colorbar to appear in the legend (with 'start' and 'stop) which shows what the color means.我希望在图例中出现一个颜色条(带有“开始”和“停止”),以显示颜色的含义。

Here is my code:这是我的代码:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx


plt.clf()
plt.plot([0,100], [0,100], '--', linewidth=3, color='k', label = 'start')
plt.plot([100,100],[0,100], '-.', linewidth=3, color = 'k', label = 'stop')



jet = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=99)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

for offset in range(1,100):
    colorVal = scalarMap.to_rgba(offset)
    plt.plot([offset, 100], [0,100], color=colorVal)

plt.legend()
plt.show()

So ideally I would have something looking like a standard colorbar, which ranges from 0 to 100, but appearing in the legend with a label 'offset' .所以理想情况下,我会有一些看起来像标准颜色条的东西,范围从 0 到 100,但出现在带有标签'offset'的图例中。

Here's some code to accomplish this based on ImportanceOfBeingErnest's comment approach (2).下面是一些基于 ImportanceOfBeingErnest 的注释方法 (2) 来完成此操作的代码。

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
from matplotlib.patches import Rectangle

fig, ax = plt.subplots(1)

plt.clf()
plt.plot([0,100], [0,100], '--', linewidth=3, color='k', label = 'start')
plt.plot([100,100],[0,100], '-.', linewidth=3, color = 'k', label = 'stop')

jet = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=99)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
scalarMap.set_array([])

for offset in range(1,100):
    colorVal = scalarMap.to_rgba(offset)
    plt.plot([offset, 100], [0,100], color=colorVal)

plt.gca().add_patch(Rectangle((0.1, 45), 40, 55, edgecolor='gray',
                                            linewidth=3, fill=False))
plt.gca().text(25, 90, "-- start")
plt.gca().text(25, 80, "-. stop")
plt.gca().text(15, 50, "  offset")

cax = fig.add_axes([0.18, 0.48, 0.03, 0.35])

plt.colorbar(scalarMap, cax = cax, ticks=[range(0, 100, 10)],
                                            orientation='vertical')

plt.show()

截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM