Xiphias
Xiphias

Reputation: 4716

Why do pyplot methods apply instantly and subplot axes methods do not?

I'm editing my graphs step by step. Doing so, plt functions from matplotlib.pyplot apply instantly to my graphical output of pylab. That's great.

If I address axes of a subplot, it does not happen anymore. Please find both alternatives in my minimal working example.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

f = plt.figure()
sp1 = f.add_subplot(1,1,1)
f.show()

# This works well
sp1.set_xlim([1,5])

# Now I plot the graph
df = pd.Series([0,5,9,10,15])
df.hist(bins=50, color="red", alpha=0.5, normed=True, ax=sp1)

# ... and try to change the ticks of the x-axis
sp1.set_xticks(np.arange(1, 15, 1))
# Unfortunately, it does not result in an instant change
# because my plot has already been drawn.
# If I wanted to use the code above,
# I would have to execute him before drawing the graph.

# Therefore, I have to use this function:
plt.xticks(np.arange(1, 15, 1))

I understand that there is a difference between matplotlib.pyplot and an axis instance. Did I miss anything or does it just work this way?

Upvotes: 2

Views: 214

Answers (2)

Francesco Montesano
Francesco Montesano

Reputation: 8668

Most of pyplot functions (if not all) have a call to plt.draw_if_interactive() before returning. So if you do

plt.ion()
plt.plot([1,2,3])
plt.xlim([-1,4])

you obtain that the plot is updated as you go. If you have interactive off, it won't create or update the plot until you don't call plt.show().

But all pyplot functions are wrappers around corresponding (usually) Axes methods.

If you want to use the OO interface, and still draw stuff as you type, you can do something like this

plt.ion()  # if you don't have this, you probably don't get anything until you don't call a blocking `plt.show`
fig, ax = plt.subplots() # create an empty plot
ax.plot([1,2,3])  # create the line
plt.draw()  # draw it (you can also use `draw_if_interactive`)
ax.set_xlim([-1,4])  #set the limits
plt.draw()  # updata the plot

You don't have to use the pyplot you don't want, just remember to draw

Upvotes: 1

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58955

The plt.xticks() method calls a function draw_if_interactive() that comes from pylab_setup(), who is updating the graph. In order to do it using sp1.set_xticks(), just call the corresponding show() method:

sp1.figure.show()

Upvotes: 1

Related Questions