0

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')
NAM
  • 9
  • 3
  • 1
    do you have a "datastes/images" folder on your filesystem relative to the python script? i can assure you, through the 10's of thousands of matplotlib figure that I have personally created, that `savefig` works – Paul H Nov 17 '20 at 01:33
  • ```''datasets/images/good.png' ``` is an relative path so it possible that you're saving it somewhere unexpected based on your current working directory. I would suggest you try importing os then adding the line ```print(os.get_cwd())``` right before saving. Alternatively you could try a saving it ```~/test_figure.png``` which will be in the root of your home directory. – benji Nov 17 '20 at 01:38
  • Given the code that you are showing, it seems to me that you are not calling ```make_plot()```. – Gealber Nov 17 '20 at 01:38
  • 1
    Yes I do have the folders. – NAM Nov 17 '20 at 01:41

1 Answers1

1

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()

Gealber
  • 463
  • 5
  • 13