0

I've been running the following lines of code and instead of adding labels and stuff to one plot, Python just creates a new plot after every command.

plt.plot(x, ydata, 'bo')
plt.plot(x,y,'r')
plt.ylabel('Dependent Variable')
plt.xlabel('Indepdendent Variable')
plt.show()

So, for example, after running the plt.ylabel() command, Python creates a new blank plot with just the y axis labeled as 'Dependent Variable'.

EDIT I've managed to solve the issue by following the steps here

Anshez
  • 7
  • 2
  • You need to provide more information. What environment are you running the code in? What backend are you using? – DavidG Sep 03 '21 at 09:46
  • anaconda3, the IDE I'm using is Spyder 5.0.5, and 'module://matplotlib_inline.backend_inline' – Anshez Sep 03 '21 at 10:08

2 Answers2

1

You could use an object oriented approach:

fig, ax = plt.subplots()

ax.plot(x, ydata, 'bo')
ax.plot(x,y,'r')
ax.set_ylabel('Dependent Variable')
ax.set_xlabel('Indepdendent Variable')

plt.show()
Zephyr
  • 11,891
  • 53
  • 45
  • 80
0

You are making two plots here, so show them separately

plt.plot(x, ydata, 'bo') #first plot
plt.show() #show the first plot


plt.plot(x, y,'r') #second plot
plt.ylabel('Dependent Variable') #second custom ylabel
plt.xlabel('Indepdendent Variable') #second custom xlabel
plt.show() #show the second plot

If you want overlaying the plots:

plt.plot(x, ydata, label='bo')
plt.plot(x, y, label='r')
plt.ylabel('Dependent Variable')
plt.xlabel('Indepdendent Variable')
plt.legend()
plt.show()
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • I'd like them to appear on the same graph. But anyway it doesn't really solve the issue. Even if I plot them separately, it still creates a new plot after every single line of code. – Anshez Sep 03 '21 at 10:28
  • @Anshez then it is something wrong with your environment try adding `%matplotlib inline` at the first line of your cell. https://stackoverflow.com/questions/43027980/purpose-of-matplotlib-inline – alec_djinn Sep 03 '21 at 10:30
  • It doesn't work either. Also, it seems my backend is already set to 'module://matplotlib_inline.backend_inline'. I am using Spyder IDE btw. – Anshez Sep 03 '21 at 12:32