MatPlotLib into WandB

I need to import MatPlotLib images into WandB. On the surface, this seems simple, since the documentation clearly shows how to ingest a plt or fig object. However, WandB is making a mess of the plots and I don’t want to recode them in plotly.
So I next want to use MatPlotLib to save a PNG and ingest that. Again seems easy, but I would prefer to do it using an in-memory buffer object (this avoids messing with local paths and temp directories on various instances). Apparently I’m not the first one to do this either (link). The instructions are clear and show someone has already done this. But it fails when I try it:

fig, (ax1, ax2) = plt.subplots(2, 1, dpi=300, figsize=(10, 5))
...
buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
wandb.log(({"chart": wandb.Image(file=buf)}))

The error seems to be with wandb.Image(). It returns:
{TypeError}__init__() got an unexpected keyword argument 'file'

I can remove the file= parameter so that the command is:

wandb.Image(buf)

And I get: {AttributeError}'_io.BytesIO' object has no attribute 'ndim'

Any recommendations?

Hi @kevinashaw!

The BytesIO type is not supported by wandb.Image which is why you are running into this issue. Here are a few options that would work instead:

  • wandb.log({ 'chart' : wandb.Image(Image.open(buf)) })
  • wandb.log({ 'chart' : wandb.Image(fig) })
  • wandb.log({ 'chart' : fig }) (Please note that this does not actually save an image but an interactable Plotly chart on your workspace

Thanks,
Ramit

1 Like

Thank you, @ramit_goolry!
The first line you provided worked perfectly!

Glad to hear! I’ll close this request for now, but if any other issues seem to pop up here, feel free to reply to this thread!

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.