0

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?

Neighbourhood
  • 166
  • 3
  • 13

2 Answers2

2

Matplotlib provides savefig which supports png and other formats.

You could, for example, do:

plt.gcf().savefig('plot.png', dpi=150)
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

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")
O.rka
  • 29,847
  • 68
  • 194
  • 309