NAM
NAM

Reputation: 29

How can I save image file using matplotlib. the method savefig not working

I am trying to save an image file using Matplotlib, but it doesn't seem to be working. If I run, it should save the file. But nothing happens. I am just testing if the image-saving-code works. So the code is actually not mine. It is taken from a python tutorial blog. please help me out.

import numpy as np
import matplotlib.pyplot as plt
def make_plot():
    t = np.arange(0.0, 20.0, 1)
    s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    s2 = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

    plt.subplot(2, 1, 1)
    plt.plot(t, s)
    plt.ylabel('Value')
    plt.title('First chart')
    plt.grid(True)

    plt.subplot(2, 1, 2)
    plt.plot(t, s2)
    plt.xlabel('Item (s)')
    plt.ylabel('Value')
    plt.title('Second chart')
    plt.grid(True)
    plt.savefig('datasets/images/good.png')

Upvotes: 0

Views: 1427

Answers (1)

Gealber
Gealber

Reputation: 483

As I said before on the comment, the problem is that you are not calling make_plot() to be excecuted. I just try your code and works perfectly fine, I had to create datasets/images folders.

import numpy as np
import matplotlib.pyplot as plt
def make_plot():
    t = np.arange(0.0, 20.0, 1)
    s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
    s2 = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

    plt.subplot(2, 1, 1)
    plt.plot(t, s)
    plt.ylabel('Value')
    plt.title('First chart')
    plt.grid(True)

    plt.subplot(2, 1, 2)
    plt.plot(t, s2)
    plt.xlabel('Item (s)')
    plt.ylabel('Value')
    plt.title('Second chart')
    plt.grid(True)
    plt.savefig('datasets/images/good.png')

# Just calling the function
make_plot()

Upvotes: 0

Related Questions