1

In the textbook about Python I am working with I read: "Every visual aspect of a graph can be changed from its default. You can specify these when you create a plot; most can also be changed later."

So creating a .py file

# simple_plot.py
import numpy as np, matplotlib.pyplot as plt
num_points = 5
x_min, x_max = 0, 4
5 x_values = np.linspace(x_min, x_max, num_points)
y_values = x_values**2
plt.plot(x_values, y_values)

and running it, gives the desired plot. Now typing in the console e.g.

plt.plot(x_values,y_values,'r--o')

plots a red dashed line with red circles at each point. However I cannot understand why typing in the console (and not adding the instructions in the script created initially) something like

plt.title("My first plot", size=24, weight='bold')
plt.xlabel("speed")
plt.ylabel("kinetic energy")

does not update the plot. Thank you very much.

4
  • Have you tried using plt.draw() after those last three lines? Commented Feb 25, 2017 at 14:44
  • What exactly do you mean by "the console"? Is it the python console you are talking about or IPython console or IPython notebook? How do you run the script? Commented Feb 25, 2017 at 15:04
  • @ spherical cowboy : Still with plt.draw() I don't see something different. Commented Feb 25, 2017 at 21:12
  • @ImportanceOfBeingErnest : I am talking about IPython console. Sorry for not being precise. Commented Feb 25, 2017 at 21:15

1 Answer 1

1

I'm assuming that you run your script (let's call it myscript.py) by calling run myscript.py in the IPython console, with the %matplotlib inline option activated.

This will plot the figure as desired into the console. However once the figure is drawn you loose the reference to it. Calling plt.plot(x_values,y_values,'r--o') creates a new figure, and plt.title(..) yet another one.

One thing you could do is work more in the object oriented way. I.e. create the figure and keep a reference in the myscript.py file like this:

import numpy as np, matplotlib.pyplot as plt
num_points = 5
x_min, x_max = 0, 4
x_values = np.linspace(x_min, x_max, num_points)
y_values = x_values**2

fig, ax = plt.subplots()
ax.plot(x_values, y_values)

then in the console you may type

ax.set_title("My Title")
ax.set_xlabel("MyLabel")

and show the figure with the updated properties anytime you like typing fig.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

It is exactly what I was looking for. Not just a workaround but a clear and concise explanation. Thank you very much for your time!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.