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')
4
  • 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 Commented Nov 17, 2020 at 1: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. Commented Nov 17, 2020 at 1:38
  • Given the code that you are showing, it seems to me that you are not calling make_plot(). Commented Nov 17, 2020 at 1:38
  • 1
    Yes I do have the folders. Commented Nov 17, 2020 at 1:41

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.