Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my plots in matplotlib not showing the axes

I am having trouble with my plots as the axes labels seem to show in Jupyter Notebooks when I was working on it.

However, when I exported the file to a .py file and ran it in terminal, the charts given do not have the axes labels..

fig = plt.figure(figsize = (15,5))

ax = fig.add_axes([0,0,1,1])
ax.set_title('Oil vs Banks Mean Return')
ax.set_xlabel('Date')
ax.set_ylabel('Price')

ax.plot(all_returns['Mean'], label = 'Banks Mean', color = 'green')
ax.plot(all_returns['Oil'], label = 'Oil', color = 'black')
ax.plot(movavg['Mean'], label = 'Mean MA', color = 'blue')
ax.plot(movavg['Oil'], label = 'OIL MA', color = 'red')

ax.legend()

plt.tight_layout();

In Jupyter Notebooks it shows the axes and labels eg. Year etc.: In Jupyter Notebooks it shows the axes and labels eg. Year etc.

However, when I export it, they are gone: However, when I export it, they are gone

like image 510
rcshon Avatar asked Dec 23 '22 04:12

rcshon


1 Answers

The line

ax = fig.add_axes([0,0,1,1])

causes the problem. Here you tell matplotlib to use all the figure space for the actual plot and leave none for the axes and labels. tight_layout() appears to have no effect if an Axes instance is created in this way. Instead, replace the line with

ax = fig.add_subplot(111)

and you should be good to go.

like image 70
Thomas Kühn Avatar answered Jan 06 '23 15:01

Thomas Kühn