nanounanue
nanounanue

Reputation: 8342

Save a matplotlib plot to a file using the command line without using plt.save()

I have a script that creates a plot and then shows it:

(The following script is an example from the docs)

# coding: utf-8
# file: test_plot.py

import yaml

import matplotlib.pyplot as plt
import numpy as np


def plot():
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2*np.pi*t)
    plt.plot(t, s)

    plt.xlabel('time (s)')
    plt.ylabel('voltage (mV)')
    plt.title('About as simple as it gets, folks')
    plt.grid(True)
    plt.show()

if __name__ == '__main__':
    plot()

If this script is executed from the command line ( python test_plot.py ) it correctly shows the plot.

The question is: It is possible to save the plot to a file without modifying the code?

Upvotes: 0

Views: 2479

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339092

Without modifying the code you can of course not change its outcome. So I will interprete this as "without modifying the plot function". I.e. you can modify anything that's below if __name__ == '__main__':.

In that case you may turn interactive mode on while calling the function and turn it off afterwards.

if __name__ == '__main__':
    plt.ion()
    plot()
    plt.ioff()
    plt.savefig("trala.png")
    plt.show()

Upvotes: 5

Related Questions