rcshon
rcshon

Reputation: 927

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

Upvotes: 12

Views: 19617

Answers (3)

C. Sanchez
C. Sanchez

Reputation: 21

I had this same issue and I will leave this solution also perhaps for me in the future.

The issue is with the subplot configuration tool subplot configuration tool

so, i just had to give more space to the display

plt.subplots_adjust(left=0.2,bottom=0.2, top = 0.9, right = 0.9)

Upvotes: 2

nbytes
nbytes

Reputation: 1

Try out this option:

color_name = "grey"
ax.spines["top"].set_color(color_name)
ax.spines["bottom"].set_color(color_name)
ax.spines["left"].set_color(color_name)
ax.spines["right"].set_color(color_name)

Upvotes: 0

Thomas Kühn
Thomas Kühn

Reputation: 9810

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.

Upvotes: 20

Related Questions