1

I'm trying to save a Matplotlib plot to an array using BytesIO as suggested here: Matplotlib save plot to NumPy array. Here is my code

import lightkurve
import matplotlib.pyplot as plt
import numpy as np
import io

def download(search):
    lc = search.download() # downloads lightcurve as lightcurve object
    if lc is not None:  
        fig,ax = plt.subplots()
        ax.scatter(lc.time.value.tolist(), lc.flux.value.tolist(), color='k')
        ax.autoscale()
        ax.set_xlabel('Time (BTJD)')
        ax.set_ylabel('Flux')
        fig.show()
        io_buf = io.BytesIO()
        fig.savefig(io_buf,format="raw")
        io_buf.seek(0)
        img_arr = np.frombuffer(io_buf.getvalue(),dtype=np.uint8)
        io_buf.close()
        return img_arr

For some reason, the returned image array only contains the repeated value 255 like so: [255 255 255 ... 255 255 255] suggesting a blank image. I've tried using plt instead of fig, autoscaling the axes in case they weren't showing, and plotting instead with the Lightkurve built-in plotting function lc.plot(ax=ax) but nothing has changed. Does anyone know how to fix this?

1 Answers1

0

I couldn't reproduce your bug. In fact, I ran your code (with some modifications) and the resulting image was exactly like the original image. Did you thoroughly check if your img_arr had only 255s? (e.g., np.unique(img_arr), in my case, len(np.unique(imgarr)) == 231)

import lightkurve
import matplotlib.pyplot as plt
import numpy as np
import io

def download(search):
    lc = search.download() # downloads lightcurve as lightcurve object
    if lc is not None:  
        fig,ax = plt.subplots()
        ax.scatter(lc.time.value.tolist(), lc.flux.value.tolist(), color='k')
        ax.autoscale()
        ax.set_xlabel('Time (BTJD)')
        ax.set_ylabel('Flux')
        fig.show()
        io_buf = io.BytesIO()
        fig.savefig(io_buf,format="raw")
        fig.savefig('test.png')  # So I could see the dimensions of the array
        io_buf.seek(0)
        img_arr = np.frombuffer(io_buf.getvalue(),dtype=np.uint8)
        io_buf.close()
        return img_arr

# I put something random -- Next time, provide this step so others can more easily debug your code. Never touched lightkurve before
search = lightkurve.search_lightcurve('KIC 757076', author="Kepler", quarter=3)
imgarr = download(search)
fig, ax = plt.subplots()
ax.imshow(imgarr.reshape(288, -1), aspect=4, cmap='gray') # Visualizing the image from the array. Got '288' from the dimensions of the png.

Original plot: enter image description here

Reconstructed plot: enter image description here

K.Cl
  • 1,615
  • 2
  • 9
  • 18
  • 1
    Thanks for your suggestion, I checked and the arrays contained about 240 unique characters. Turned out my issue was with some machine learning code later on, fixed it and everything works. Thank you! – Sophie Frankel Jul 29 '22 at 19:36