Home > database >  matplotlib plt.show() doesn't show anything if axis is added after defining figure
matplotlib plt.show() doesn't show anything if axis is added after defining figure

Time:09-28

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.

CodePudding user response:

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

  • Related