Dread Pirate Roberts
Dread Pirate Roberts

Reputation: 539

Why is plt.savefig not saving any file at all?

I seem to be having a strange situation wherein plt.savefig seems not to save any file at all.

The code is of the form of

df.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.savefig(label + "_" + "Plot_Type_Name.png", bbox_inches="tight")
plt.close("all")

and it is being run from a command-line and/or from PyCharm. It's not apparent to me why it's failing. Can anyone help?

Upvotes: 0

Views: 6883

Answers (2)

Akshay Gulabrao
Akshay Gulabrao

Reputation: 3

savefig() needs to be before show()

Upvotes: -1

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

The code from the question will save a figure under the condition that df is defined and df.plot() creates a plot. Here is a full working example:

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

df = pd.DataFrame({"x":np.arange(5),"y":np.random.rand(5)})

df.plot().legend(loc='center left', bbox_to_anchor=(1, 0.5))

fname="label.png"
plt.savefig(fname, bbox_inches="tight")
plt.close("all")

You may test that the file is actually there

import os
if os.path.exists(fname):
    print(os.path.abspath(fname))
else:
    print("file not found")

Upvotes: 2

Related Questions