python线条颜色不同,Python:如果超出特定范围,是否可以更改图中的线条颜色?...

Is it possible to change the line color in a plot when values exceeds a certain y value?

Example:

import numpy as np

import matplotlib.pyplot as plt

a = np.array([1,2,17,20,16,3,5,4])

plt.plt(a)

This one gives the following:

lYW5o.png

I want to visualise the values that exceeds y=15. Something like the following figure:

Eicv8.png

Or something like this(with cycle linestyle):

monap.png:

Is it possible?

解决方案

Unfortunately, matplotlib doesn't have an easy option to change the color of only part of a line. We will have to write the logic ourselves. The trick is to cut the line up into a collection of line segments, then assign a color to each of them, and then plot them.

from matplotlib import pyplot as plt

from matplotlib.collections import LineCollection

import numpy as np

# The x and y data to plot

y = np.array([1,2,17,20,16,3,5,4])

x = np.arange(len(y))

# Threshold above which the line should be red

threshold = 15

# Create line segments: 1--2, 2--17, 17--20, 20--16, 16--3, etc.

segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)

segments_y = np.r_[y[0], y[1:-1].repeat(2), y[-1]].reshape(-1, 2)

# Assign colors to the line segments

linecolors = ['red' if y_[0] > threshold and y_[1] > threshold else 'blue'

for y_ in segments_y]

# Stamp x,y coordinates of the segments into the proper format for the

# LineCollection

segments = [zip(x_, y_) for x_, y_ in zip(segments_x, segments_y)]

# Create figure

plt.figure()

ax = plt.axes()

# Add a collection of lines

ax.add_collection(LineCollection(segments, colors=linecolors))

# Set x and y limits... sadly this is not done automatically for line

# collections

ax.set_xlim(0, 8)

ax.set_ylim(0, 21)

jfrKu.png

Your second option is much easier. We first draw the line and then add the markers as a scatterplot on top of it:

from matplotlib import pyplot as plt

import numpy as np

# The x and y data to plot

y = np.array([1,2,17,20,16,3,5,4])

x = np.arange(len(y))

# Threshold above which the markers should be red

threshold = 15

# Create figure

plt.figure()

# Plot the line

plt.plot(x, y, color='blue')

# Add below threshold markers

below_threshold = y < threshold

plt.scatter(x[below_threshold], y[below_threshold], color='green')

# Add above threshold markers

above_threshold = np.logical_not(below_threshold)

plt.scatter(x[above_threshold], y[above_threshold], color='red')

LDHgJ.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值