Skip to content
Home » matplotlib Part 14 – Twin Axes

matplotlib Part 14 – Twin Axes

Spread the love

Twin Axes

Sometimes you may want to display two independent axes at the same time, like for example when you plot two different quantities on one graph. You can use the twinx or twiny method, depending on which twin axis you want to create. Let’s demonstrate it on an example with a shared X axis and two independent Y axes. We’ll graph the time and the cost of a journey against distance. We’ll have distance on the X axis, time and cost on two independent Y axes:

In [10]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# The t values will represent the distance from 0 to 100 km.
d = np.linspace(0, 100, 1000)

# We're moving in a stagecoach, so pretty slowly. Let's assume we're moving at 8km/h.
t = d/8

# Suppose you have to pay $40 the moment you get into the stagecoach, then the price is $10 for each ten kilometers you start. 
# Who said it was going to be cheap?
c = 40 + np.int16(d/10) * 10

# Let's create the first of the twin axes.
fig, ax_time = plt.subplots(figsize=(16, 8))

# Let's use the red color for the time against distance plot.
ax_time.plot(d, t, color='r')

# Let's set the title and axis and tick labels.
ax_time.set_title('Trip Time and Cost', fontsize=18)
ax_time.set_xlabel('distance [km]')
ax_time.set_ylabel('time [h]', color='r')
for label in ax_time.get_yticklabels():
    label.set_color('r')
    
# Let's create the other of the twin axes. They should share the X axis.
ax_cost = ax_time.twinx()

# Let's use the blue color for the cost against distance plot.
ax_cost.plot(d, c, color='b')

# Let's set the axis and tick labels.
ax_cost.set_ylabel('cost in US dollars', color='b')
for label in ax_cost.get_yticklabels():
    label.set_color('b')

Now you can see, for example, that a 48 km trip will take 6 hours and it will cost you a total of $80. Maybe you should consider taking a train?

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply