Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing line style for certain range of values using matplotlib

I need to reproduce plots of this type (bifurcation plots) -

bifurcation plot

I tried to follow the example given at change-matplotlib-line-style-mid-graph, but couldn't really work it out. Could someone give a tip?

like image 575
Ohm Avatar asked Mar 19 '26 09:03

Ohm


1 Answers

In the following I have put together 4 different examples. They show different things:

  1. The simplest way to recreate the graph in your question. Note, that each line is only defined by two points.
  2. This is what I assume you have: two x and y vectors that define each line (in my example they each have 100 values).
  3. This one is most interesting for you (I guess): The vectors solid1 and solid2 are used to select the values of x and y, that satisfy the conditions.
  4. Just to show you how you can put the spines in the center (since the graph in your question has them centered).

enter image description here

Code:

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(12,4))

# Example 1
plt.subplot(1,4,1)
line1 = np.array([[-1,0],[0,0]])
line2 = np.array([[0,0],[1,1]])
line3 = np.array([[-1,-1],[0,0]])
line4 = np.array([[0,0],[1,0]])
plt.plot(line1[:,0], line1[:,1], 'b', linewidth=4)
plt.plot(line2[:,0], line2[:,1], 'b', linewidth=4)
plt.plot(line3[:,0], line3[:,1], 'b--', linewidth=4)
plt.plot(line4[:,0], line4[:,1], 'b--', linewidth=4)

# Example 2
plt.subplot(1,4,2)
x1 = np.linspace(-1,1,100)
x2 = np.linspace(-1,1,100)
y1 = x1*0
y2 = x2
plt.plot(x1,y1,'r', linewidth=4)
plt.plot(x2,y2,'g', linewidth=4)

# Example 3
plt.subplot(1,4,3)
#some sort of split condition:
solid1 = x1<0
solid2 = x2>0
#plot each line in two seperate plot calls
plt.plot(x1[solid1], y1[solid1], 'r', linewidth=4)
plt.plot(x1[np.logical_not(solid1)], y1[np.logical_not(solid1)], 'r--', linewidth=4)
plt.plot(x2[solid2], y2[solid2], 'g', linewidth=4)
plt.plot(x2[np.logical_not(solid2)], y2[np.logical_not(solid2)], 'g--', linewidth=4)

# Example 4 
plt.subplot(1,4,4)
# put the spines to the middle
ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()
like image 103
hitzg Avatar answered Mar 21 '26 23:03

hitzg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!