Ask Your Question
1

Two Y-axes

asked 2011-12-16 16:17:35 +0100

v_2e gravatar image

Hello! Could somebody please point me to a way of plotting two curves associated with different y-axes? I need to plot two curves with different scale over the y-axis to compare their form. What I was thinking of is having two separate y-axes on both sides of a plot and associating one of the curves with the left axis and the other one - with the right axis. Is that possible?

Thank you.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2011-12-16 17:41:40 +0100

v_2e gravatar image

updated 2011-12-16 17:43:57 +0100

A self-answer (the idea is taken from here):

# Let's create two lists with some data
curve1 = []
for x in range(0,10):
    curve1.append((x,n(sin(x))))

curve2 = []
for x in range(0,100):  
    curve2.append((x/10,n(10*sin(x/10+1))))


import matplotlib.pyplot as plt
fig = plt.figure()
# Create the first Y-axis on the left by default and
# plot the first curve associated to the left Y-axis
ax1 = fig.add_subplot(111)
curve1_x = zip(*curve1)[0]
curve1_y = zip(*curve1)[1]
ax1.plot(curve1_x, curve1_y, '.-', color='red')

# Paint the tick labels on the left Y-axis in red 
# to match the color of a curve
for tl in ax1.get_yticklabels():
    tl.set_color('red')

# Create the second Y-axis on the right and
# plot the second curve associated to the right Y-axis
ax2 = ax1.twinx()
curve2_x = zip(*curve2)[0]
curve2_y = zip(*curve2)[1]
ax2.plot(curve2_x, curve2_y, '.-', color='blue')

# Paint the tick labels on the left Y-axis in blue 
# to match the color of a curve
for tl in ax2.get_yticklabels():
    tl.set_color('blue')

# Create the vertical and horizontal grid lines
ax1.xaxis.grid(color='grey', linestyle='--', linewidth=0.5)
ax1.yaxis.grid(color='grey', linestyle='--', linewidth=0.5)

# Save the figure (to see it in Sage)
plt.savefig('figure.png')
edit flag offensive delete link more

Comments

I'm trying to mimic your solution for this: phi = var('phi') a=2 q1=a*phi^2+1 q2=a*phi^2+2000 t1=q1.plot(aspect_ratio=1,xmin=0,xmax=10) t2=q2.plot(aspect_ratio=1,xmin=0,xmax=10) z=t1+t2 z.show(xmin=0,xmax=10,ymin=0,ymax=300,aspect_ratio=.02) But I had no success. Do you know how I should proceed?

Jorge gravatar imageJorge ( 2014-10-12 05:08:48 +0100 )edit

@Jorge Why do you call this "mimic"? You are trying to use the Sage wrappers around Matplotlib functions, while I used those functions directly instead. That was the whole purpose of building such a long algorithm instead of the short one like yours.

v_2e gravatar imagev_2e ( 2015-06-15 20:29:19 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2011-12-16 16:17:35 +0100

Seen: 1,268 times

Last updated: Dec 16 '11