I needed to make a plot using pandas and matplotlib. I am using python3.9 and tried the code in IPython. The matplotlib version is 3.3.2, and that of pandas 1.1.5. What I get, is unreadable text showed in the terminal with no plot being generated. Here is the code:
#Three lines to make the compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
df["Duration"].plot(kind = 'hist')
plt.show()
#Two lines to make the compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
What is the reason behind ?
plt.savefig(...)beforeplt.show(), because as a side effectplt.show()erases the plot.plt.savefig(...)at the end as I have done it ? An argument is required for theplt.savefig(...). What should I put as argument ?plt.show().plt.savefig(filename)is used to save a plot to a file. Where does the idea of usingsys.stdout.buffercome from? Is it some really old code? Or are you using a very unusual environment?matplotlib.use('Agg')(and restart the environment) to let matplotlib work with its defaults? If you are running jupyter, you may need%matplotlib inline(just an image) or%matplotlib notebook(interactive plot). See also here and hereplt.savefig('filename'), the plot is not saved and not displayed. I only get the following message, which I also get if I save the plot: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.