首页 > 解决方案 > python - 如何根据python中一个图形中不同图的一个变量获得不同的线条颜色?

问题描述

假设我有一个带有一定数量地块的图形,类似于这个: 在此处输入图像描述

其中单个图的颜色由 matplotlib 自动决定。获取它的代码非常简单:

for i in range(len(some_list)):
    x, y = some_function(dataset, some_list[i])
    plt.plot(x, y) 

现在假设所有这些行都依赖于第三个变量 z。我想包含这些信息,用一种颜色绘制给定的线,该颜色提供有关 z 大小的信息,可能使用图右侧的颜色图和颜色条。你会建议我做什么?我排除使用图例,因为在我的图中我有更多的线条,而不是我展示的线条。我能找到的所有信息都是关于如何用不同颜色绘制一条线,但这不是我想要的。我提前谢谢你!

标签: pythonmatplotlibplotdata-visualizationfigure

解决方案


这是一些代码,在我看来,您可以轻松适应您的问题

import numpy as np
import matplotlib.pyplot as plt
from random import randint

# generate some data
N, vmin, vmax = 12, 0, 20
rd = lambda: randint(vmin, vmax)
segments_z = [((rd(),rd()),(rd(),rd()),rd()) for _ in range(N)]

# prepare for the colorization of the lines,
# first the normalization function and the colomap we want to use
norm = plt.Normalize(vmin, vmax)
cm = plt.cm.rainbow
# most important, plt.plot doesn't prepare the ScalarMappable
# that's required to draw the colorbar, so we'll do it instead
sm = plt.cm.ScalarMappable(cmap=cm, norm=norm)

# plot the segments, the segment color depends on z
for p1, p2, z in segments_z:
    x, y = zip(p1,p2)
    plt.plot(x, y, color=cm(norm(z)))

# draw the colorbar, note that we pass explicitly the ScalarMappable
plt.colorbar(sm)

# I'm done, I'll show the results,
# you probably want to add labels to the axes and the colorbar.
plt.show()

在此处输入图像描述


推荐阅读