python - python - 如何根据python中一个图形中不同图的一个变量获得不同的线条颜色?
问题描述
其中单个图的颜色由 matplotlib 自动决定。获取它的代码非常简单:
for i in range(len(some_list)):
x, y = some_function(dataset, some_list[i])
plt.plot(x, y)
现在假设所有这些行都依赖于第三个变量 z。我想包含这些信息,用一种颜色绘制给定的线,该颜色提供有关 z 大小的信息,可能使用图右侧的颜色图和颜色条。你会建议我做什么?我排除使用图例,因为在我的图中我有更多的线条,而不是我展示的线条。我能找到的所有信息都是关于如何用不同颜色绘制一条线,但这不是我想要的。我提前谢谢你!
解决方案
这是一些代码,在我看来,您可以轻松适应您的问题
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()
推荐阅读
- prolog - Prolog - 数组数组,返回数组长度大于一的条目
- reactjs - 在 TS 中动态导出 React 组件
- python - 在 venv 的 pip list 时如何解决此导入错误?
- angular-cli - 为什么在构建 Angular 应用程序(npm run build)时需要添加“运行”参数?
- javascript - 如何添加所需的反应选择?
- python-3.x - 在请求中实现身份验证发送到 LDAP 服务器以在 python3 中进行连接
- asp.net-core - 脚手架身份时“运行所选代码生成器时出错”
- r - 如何在 r 中重定向系统命令及其输出?
- python - 宽到长数据帧 - 使用时间戳作为索引时出错
- docker - /bin/bash:第 117 行:kubectl:找不到命令 gitlab-ci