0

I have a problem with plotting through matplotlib.

When I try to plot with this code works well:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.plot(10)
plt.show()

But when I try this one, doesn't work:

import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.plot(10)
plt.show()

Does someone know why this happens?

My matplotlib version is 3.3.4

Many thanks.

Hayoung
  • 347
  • 2
  • 11

1 Answers1

0

Take a closer look at the second line of your second code snippet, you're capitalizing the letter "f" in plt.Figure, it should be plt.figure instead. Bellow is the corrected version:

import matplotlib.pyplot as plt
fig = plt.figure() 
ax = fig.add_subplot(111)
ax.plot(10)
plt.show()

Your output will be:

enter image description here

personaltest25
  • 272
  • 2
  • 11
  • It works well, thank you! I have one remaining (not important) question that why does it seems fig and ax are created normally (I can even access line values which I assigned to ax)? – Hayoung Sep 28 '21 at 08:38
  • `plt.Figure` is a class, not a method. `plt.figure()` is a method (function) which creates an instance of the `Figure` class. So in your version that doesn't work, you are creating a `Figure`, but probably not initialising all the elements of it that are needed to properly display it. – tmdavison Sep 28 '21 at 09:07
  • @Hayoung, look at this answer, https://stackoverflow.com/a/34162641/14195255 its very well explained. – personaltest25 Sep 28 '21 at 09:07