I am learning DataAnlaysis and was working with matplotlib.pyplot
.
I was plotting a Bar Graph using matplotlib.pyplot.bar()
in Jupyter files.
I used plt.show()
to have a idea about the figure, but it is not producing any output.
I tried saving the figure, it is saving an blank image.
The Strange thing is, when I put all of my code in a same Notebook cell
.. it works! It saves the figure and plt.show()
working as well.
But it doesn't when I separate them in different cells.
I've tried restarting kernal and running all cells on one go.
Here is my code..
%matplotlib inline
from matplotlib import pyplot as plt
past_years_averages = [82, 84, 83, 86, 74, 84, 90]
years = [2000, 2001, 2002, 2003, 2004, 2005, 2006]
error = [1.5, 2.1, 1.2, 3.2, 2.3, 1.7, 2.4]
plt.figure(figsize=(10, 8))
plt.bar(range(len(past_years_averages)), past_years_averages, yerr=error, capsize=5)
plt.axis([-0.5, 6.5, 70, 95])
ax = plt.subplot()
ax.set_xticks(range(len(years)))
ax.set_xticklabels(years)
plt.title("Final Exam Averages")
plt.xlabel("Year")
plt.ylabel("Test average")
plt.savefig("my_bar_chart.png")
plt.show()
CodePudding user response:
Tried replicating your code in colab, It indeed works fine when run in a single cell.
The reason for getting blank output while segregating the code into different cells is:
The plot is generated as soon as the cell comprising plt.axis
is run.
After that, all operations are done on the axis, whose axis? Is not specified so a new plotting window is created (this gives a blank plot).
I would advise you to run the plotting statements in a single cell, as colab shows output as soon as something related to matplotlib is run thereby making the axis of previous plot inaccessible. And all subsequent operations are run on a fresh figure.