Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting active subplot using axes object in matplotlib?

Tags:

The object oriented matplotlib subplots interface is nice, but I am having difficulty using it when calling a function that contains lines like plt.plot(x, y). These functions work with plt.subplot() easily, but is it possible to set the active subplot with a given axes object? Specifically I want something like the following to plot into two seperate subplots:

import matplotlib.pyplot as plt

x = [0 ,1, 2]
y= [0 ,1 2]

fig, axs = plt.subplots(2,1)

plt.some_function_to_set_active_subplot(axs[0])
plt.plot(x, y)

plt.some_function_to_set_active_subplot(axs[1])
plt.plot(x, y)

Does any such function some_function_to_set_active_subplot exist?

Edit: I specifically cannot use ax.plot, or anything like that. I am basically asking about how to mix the object oriented interface with the matlab style interface.

Edit 2: I don't want to use plt.subplot either. I want to use OO interface for setting up subplots, and matlab-style for the actual plotting.

like image 535
nbren12 Avatar asked Jun 25 '14 19:06

nbren12


2 Answers

You can use plt.axes to set the current active axes. From the documentation: "axes(h) where h is an axes instance makes h the current axis."

import matplotlib.pyplot as plt

x = [0 ,1, 2]
y = [10 ,20, 30]

fig, axs = plt.subplots(2,1)

plt.axes(axs[0])
plt.plot(x,y)
plt.axes(axs[1])
plt.plot(y,x)
plt.show()
like image 91
Molly Avatar answered Oct 15 '22 19:10

Molly


The method plt.axes is deprecated for this use. Use plt.sca instead. Following the example above:

import matplotlib.pyplot as plt

x = [0 ,1, 2]
y = [10 ,20, 30]

fig, axs = plt.subplots(2,1)

plt.sca(axs[0])
plt.plot(x,y)
plt.sca(axs[1])
plt.plot(y,x)
plt.show()
like image 29
mm_ Avatar answered Oct 15 '22 21:10

mm_