Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - Change matplotlib line style mid-graph

I'm graphing some data (two lines) and I'd like to change the line style for the portions of the lines where the difference between them is statistically significant. So, in the below image (now a link b/c anti-spam policies don't allow me to post an image) I'd like the lines to look different (i.e. dashed perhaps) up until they start converging at about 35 on the x axis.

line plot

Is there a way to do this easily? I have the values for the x axis where the differences are significant, I'm just not clear how to change line styles at certain x-axis locations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: I'd had this open and left, so I didn't notice @Ricardo's answer. Because matplotlib will convert things to numpy arrays regardless, there are more efficient ways to do it.

As an example:

Just plot two different lines, one with a dashed linestyle and another with a solid linestyle.

E.g.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y1 = 2 * x
y2 = 3 * x

xthresh = 4.5
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(x[below], y1[below], 'b--')
plt.plot(x[below], y2[below], 'g--')

# Plot lines above threshold as solid...
plt.plot(x[above], y1[above], 'b-')
plt.plot(x[above], y2[above], 'g-')

plt.show()

enter image description here

For the case where they're cyclic, use masked arrays:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 100)
y1 = 2 * np.cos(x)
y2 = 3 * np.sin(x)

xthresh = 2.0
diff = np.abs(y1 - y2)
below = diff < xthresh
above = diff >= xthresh

# Plot lines below threshold as dotted...
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y1), 'b--')
plt.plot(np.ma.masked_where(below, x), np.ma.masked_where(below, y2), 'g--')

# Plot lines above threshold as solid...
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y1), 'b-')
plt.plot(np.ma.masked_where(above, x), np.ma.masked_where(above, y2), 'g-')

plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...