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.
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With