Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

python - How to call plt.subplots() without opening GUI?

I want to run a deep learning training that uses matplotlib internally for creating graphs and then use the created figure and dump it to disk as image.

The dumping part is done for me using tensorboardX and that part works.

The problem:

plt.subplots(4, 1) opens a window, which slows down my program, especially when not all figures get closed upon request.

I want the same functionality without GUI:

  • Create the subplots.
  • Plot into them.
  • Have a figure object with the plots drawn (and not shown on screen) and do whatever I want with it.

Sample code (in pytorch-lightning) for context only, I don't expect anyone to have to reproduce this, as the question is clear.

tb = self.logger.experiment
fig, axs = plt.subplots(n_plots, 1)
    for sample_idx in range(n_plots):
        for feature_idx, (orig_feature, recon_feature) in enumerate(zip(orig_batch_view[sample_idx + first_sample_idx, :, :], recon_batch_view[sample_idx + first_sample_idx, :, :])):
            i = feature_idx
            if i > 0: continue  # or scale issues don't allow informative plotting                     

                axs[sample_idx].plot(orig_feature.detach().cpu().numpy(), label=f'orig{i}, sample{sample_idx}')
                axs[sample_idx].plot(recon_feature.detach().cpu().numpy(), label=f'recon{i}, sample{sample_idx}')
          
                axs[sample_idx].legend(loc='upper left')
    tb.add_figure(f"{mode}recon_vs_orig", fig, global_step=self.current_epoch, close=True)

Can it be done?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inspired by @Mr.T, I investigated some more and got a similar solution with different syntax.

matplotlib.use('Agg')  # turn off gui
fig, axs = plt.subplots(n_plots, 1)
...
matplotlib.use('QT4Agg')  # turn on gui

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...