4
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)  
df_new = pd.DataFrame(np.random.randn(5,3), columns=list('ABC'))

df_new.plot(kind='bar')

I have no idea about weather I have to use plt.show() or not. Because if there is only df_new.plot(kind='bar'),it will shows the plot. If I add plot.show(),it shows also. What is the difference between them? I use Jupyter. Thanks in advance.

  • 1
    Depends on the IDE. Is this Jupyter or something else? There are lots of things you might want to do before the figure is displayed, but I guess something else is smart enough to know that the script has ended and you want a plot in your plot window – roganjosh Nov 10 '19 at 14:32
  • 1
    By default you need `plt.show`, but some environments (newer ipython and jupyter among others) automatically enable interactive mode (`plt.ion()`) for you, which implies you _don't_ have to call this to get your figures. See also [the official FAQ](https://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode) – Andras Deak -- Слава Україні Nov 10 '19 at 15:21

3 Answers3

2

I guess your using interactive tool like jupyter.
In case of jupyter as you said df.plot(kind ='bar') displays the graph.
In interactive tools, You need to use plt.show() when all your plots are created.

  import matplotlib.pyplot as plt
  plt.plot(x, y)
  plt.plot(y,z)
  plt.show()

In python IDLE if you just use df.plot((kind = 'bar'), it won't displays the graph on run.
To display the graph without using plt.show() in IDLE you can follow the following steps.

 import matplotlib.pyplot as plt
 from matplotlib import interactive
 import pandas as pd
 import numpy as np

 #Set interactive mode to True
 interactive(True)
 df = pd.DataFrame(np.random.randn(5,3), columns = list('ABC'))
 df.plot(kind = 'bar')

I hope this answers your question.

Gags08
  • 240
  • 2
  • 9
0

I tried your code, without the plt.show(), the figure doesn't show. I think it depends on what IDE you are using. So please use the plt.show() for reproducibility.

Bill Chen
  • 1,699
  • 14
  • 24
0

df_new.plot(kind='bar') will instantiate and return object of plt, something like:"", so you have to call plt.show() for this object to see your plot. Here is what happen when you call plt.show(); show() function will draw plot property of the last created object of plt. Hope it helps.

Abdirahman
  • 180
  • 1
  • 5
  • The reason you see the figure in jupyter is that in jupyter you will see the result of the last operation executed in your code snippet, for example: if you write 7+5 as the last line of your code snippet and execute your code 12 will be displayed as result although you didn't write print(7+5). – Abdirahman Nov 10 '19 at 15:04