python 画线条进行到指定区域更改颜色_Python: 如果超过一定范围, 是否可以更改图形上线条的颜色?...

本文介绍如何在Python中使用matplotlib库创建线条,并根据线条上的点值超过特定阈值时改变颜色。通过定义辅助函数`threshold_plot`,可以实现当y值大于阈值时,线条颜色从一种颜色变为另一种颜色。示例展示了如何设置颜色映射和边界规范,以在散点图和线图上应用这种效果。
摘要由CSDN通过智能技术生成

定义一个辅助功能(这是一个简单功能, 可以添加更多功能)。此代码是文档中此示例的小重构

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.collections import LineCollection

from matplotlib.colors import ListedColormap, BoundaryNorm

def threshold_plot(ax, x, y, threshv, color, overcolor):

"""

Helper function to plot points above a threshold in a different color

Parameters

----------

ax : Axes

Axes to plot to

x, y : array

The x and y values

threshv : float

Plot using overcolor above this value

color : color

The color to use for the lower values

overcolor: color

The color to use for values over threshv

"""

# Create a colormap for red, green and blue and a norm to color

# f' < -0.5 red, f' > 0.5 blue, and the rest green

cmap = ListedColormap([color, overcolor])

norm = BoundaryNorm([np.min(y), threshv, np.max(y)], cmap.N)

# Create a set of line segments so that we can color them individually

# This creates the points as a N x 1 x 2 array so that we can stack points

# together easily to get the segments. The segments array for line collection

# needs to be numlines x points per line x 2 (x and y)

points = np.array([x, y]).T.reshape(-1, 1, 2)

segments = np.concatenate([points[:-1], points[1:]], axis=1)

# Create the line collection object, setting the colormapping parameters.

# Have to set the actual values used for colormapping separately.

lc = LineCollection(segments, cmap=cmap, norm=norm)

lc.set_array(y)

ax.add_collection(lc)

ax.set_xlim(np.min(x), np.max(x))

ax.set_ylim(np.min(y)*1.1, np.max(y)*1.1)

return lc

使用范例

fig, ax = plt.subplots()

x = np.linspace(0, 3 * np.pi, 500)

y = np.sin(x)

lc = threshold_plot(ax, x, y, .75, 'k', 'r')

ax.axhline(.75, color='k', ls='--')

lc.set_linewidth(3)

然后退出

e16a2ab303618a363075b9cc54e63505.png

如果只希望标记改变颜色, 请使用相同的比率和cmap并将其传递到散点图

cmap = ListedColormap([color, overcolor])

norm = BoundaryNorm([np.min(y), threshv, np.max(y)], cmap.N)

sc = ax.scatter(x, y, c=c, norm=norm, cmap=cmap)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值