Search code examples
pythonpython-3.xnumpymatplotlibgoogle-colaboratory

My fig1.savefig function is saving my figure as a blank screen, how do I fix this?


I am importing data by a .csv file and am plotting it, but when I plot my figure and try to save it to my google drive it only saves a blank image with none of the data. I am using Google Collaboratory.

Here is my code:

#Displaying the Data


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

plt.title("Score of Each Raisan Thrown", fontsize ='x-large')

plt.ylabel("Valid Raisans Thrown", fontsize='large')
plt.xlabel("Score", fontsize= 'large')

dart = data[:,0]
score =  data[:,1]

plt.plot(score ,dart, marker='o', linestyle='none', color='black')

ax = plt.subplot()

ax.set_facecolor('seashell')

# Adding ticks to make my plot easier to understand/read

ax.set_yticks([20,40,60,80,100,120,140,160,180,200])
ax.set_xticks([-16,-14,-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12,14,-16])

fig = plt.figure(figsize=(10,5))

fig = plt.gcf()
plt.draw()
fig.savefig(datapath+'My Experiment1 Plot')

plt.show()



Solution

  • Because your

    fig = plt.figure(figsize=(10,5))
    
    fig = plt.gcf()
    plt.draw()
    fig.savefig(datapath+'My Experiment1 Plot')
    

    comes after all the drawing commands, which means you are creating a new figure without plotting anything and just save it. You need to rearrange your commands:

    # get the data:
    dart = data[:,0]
    score =  data[:,1]
    
    # set up the fig and axes:
    fig, ax = plt.subplots(figsize=(10,5))
    
    # plot the data
    plt.plot(score ,dart, marker='o', linestyle='none', color='black')
    
    # additional formatting
    plt.title("Score of Each Raisan Thrown", fontsize ='x-large')
    plt.ylabel("Valid Raisans Thrown", fontsize='large')
    plt.xlabel("Score", fontsize= 'large')
    
    # even more formatting
    ax.set_facecolor('seashell')
    
    # Adding ticks to make my plot easier to understand/read    
    ax.set_yticks([20,40,60,80,100,120,140,160,180,200])
    ax.set_xticks([-16,-14,-12,-10,-8,-6,-4,-2,0,2,4,6,8,10,12,14,-16])
    
    fig.savefig(datapath+'My Experiment1 Plot')
    
    plt.show()