Python Forum

Full Version: Using matplotlib in Spyder v/s REPL
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I am just starting off with Python and was playing around with matplotlib package.
I wrote a few lines as below to plot a graph
def plotgrh():
  import matplotlib.pyplot as plt
 
  fig, ax = plt.subplots(1,2)
  print("I am plotting graph")
  plt.plot([6,1,8,4],[4,7,2,1])
  print("Graph plotted")
I am able to import the above module and run plotgrh() in Spyder. I can see the graph plotted in the "Plots" tab in Spyder console.The msgs I am printing also get displayed. But if I open a powershell prompt, start python and run plotgrh() in the Python prompt (>>>), then only the print msgs are displayed but the graph is not displayed. What is need to get the graph plotted? Should I include any additional modules? The reason I need this is, I am trying to create some scripts that will plot graphs and want to be able to run them as a Windows application or from a DOS command prompt and not from within Spyder. Any suggestions/pointers is highly appreciated.
You could try plt.show(block=False) perhaps.
If this running outside a environment like Sypder/REPL/Notebook.
The need to use plt.show() to show the plot.
import matplotlib.pyplot as plt

def plotgrh():
    fig, ax = plt.subplots(1,2)
    print("I am plotting graph")
    plt.plot([6,1,8,4],[4,7,2,1])
    # Uncomment for save plot
    #plt.savefig('Graph.png')
    plt.show()
    print("Graph plotted")

plotgrh()