Neighbourhood
Neighbourhood

Reputation: 336

How to fix error with saving plots in matplotlib?

I have this code:

plt.figure(figsize=(24, 9))
function_names = ['Loss', 'Accuracy']
stats_names = iter(list(stats.keys()))

for i in range(2):
    ax = plt.subplot(1, 2, i+1)
    ax.plot(range(config['n_train_epoch']),
            stats[next(stats_names)], 
            label='Validation', 
            color='darkorchid', 
            lw=2.5)
    ax.plot(range(config['n_train_epoch']), 
            stats[next(stats_names)], 
            label='Training', 
            color='mediumspringgreen', 
            lw=2.5)
    ax.set_xlabel('Number of training epochs')
    ax.set_ylabel(function_names[i] + ' value')
    ax.set_title(function_names[i] + ' Functions', fontsize=20)
    ax.legend(fontsize=14)

And i`m getting this plots.

I want to save it to png, but when i refactor my code to this:


plt.figure(figsize=(24, 9))
function_names = ['Loss', 'Accuracy']
stats_names = iter(list(stats.keys()))

for i in range(2):
    ax = plt.subplot(1, 2, i+1)
    ax.plot(range(config['n_train_epoch']),
            stats[next(stats_names)], 
            label='Validation', 
            color='darkorchid', 
            lw=2.5)
    ax.plot(range(config['n_train_epoch']), 
            stats[next(stats_names)], 
            label='Training', 
            color='mediumspringgreen', 
            lw=2.5)
    ax.set_xlabel('Number of training epochs')
    ax.set_ylabel(function_names[i] + ' value')
    ax.set_title(function_names[i] + ' Functions', fontsize=20)
    ax.legend(fontsize=14)

plt.savefig('results/graphics.png')

i`m getting this

What is the problem?

Upvotes: 0

Views: 1113

Answers (2)

O.rka
O.rka

Reputation: 30677

I would recommend instantiating your figures and axes directly. It's much easier to manipulate and save plots.

For example,

with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots()
    # Plot something using `ax`
    fig.savefig("path/to/output.png", dpi=300, bbox_inches="tight")

Upvotes: 0

Marcin
Marcin

Reputation: 238081

Matplotlib provides savefig which supports png and other formats.

You could, for example, do:

plt.gcf().savefig('plot.png', dpi=150)

Upvotes: 0

Related Questions