1

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 ?

7
  • 1
    Something important is to call plt.savefig(...) before plt.show(), because as a side effect plt.show() erases the plot. Commented Jan 2, 2021 at 12:45
  • Thanks. Do I have to also call plt.savefig(...) at the end as I have done it ? An argument is required for the plt.savefig(...). What should I put as argument ? Commented Jan 2, 2021 at 13:53
  • 2
    To just display the plot, you normally only need plt.show(). plt.savefig(filename) is used to save a plot to a file. Where does the idea of using sys.stdout.buffer come from? Is it some really old code? Or are you using a very unusual environment? Commented Jan 2, 2021 at 13:57
  • 2
    What happens if you leave out 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 here Commented Jan 2, 2021 at 14:21
  • I only need to see the plot and not save it to a file. I followed your suggestion. I got the plot saved in the working directory folder. When I omit the last two lines, I do not get the unreadable text I was complaining before. Thanks for your suggestion. If I do not save the plot via plt.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. Commented Jan 2, 2021 at 14:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.