Making PNG with a transparent background in PyGMT

Greetings dear PyGMT community,

my task is to produce maps with transparent background using PyGMT, so that I don’t need to manually delete white background in some graphical editor after.
As I understood, the only thing that I need to do is to activate transparency option in the pygmt.Figure.savefig. The problem is that even if I do so, I still get figures with the white background.

Maybe I am missing something?

My final line in the code looks like this: fig.savefig("Filename.png", transparent=True)

Yes, for example this produces a transparent figure:

import pygmt
fig = pygmt.Figure()
fig.basemap(region=[-90, -70, 0, 20], projection="M8i", frame=True)
fig.savefig("test-fig.png",transparent=True)

Does this produce a non-transparent background for you? If so, can you please post the output from pygmt.show_versions()?

1 Like

I’m guessing Ghostscript issue?

Hello Meghanj,

thank you for your answer. Your example worked for me as well. In fact, I recognized that the problem was that I had an element on my map with an activated transparency option.

So, your example will not work for me if for instance I want to add semi-transparent gridlines:

import pygmt
fig = pygmt.Figure()
fig.grdimage(grid='@earth_relief_10m',region=[-90, -70, 0, 20],projection="M8i")
fig.basemap(region=[-90, -70, 0, 20], projection="M8i", frame=["+n","xg5", "yg5"],t=50)
fig.basemap(region=[-90, -70, 0, 20], projection="M8i", frame=["xa5f5", "ya5f5"])
fig.savefig("test-fig.png",transparent=True)
fig.show()

As soon as I deactivate -t option everywhere apart from fig.savefig command, I get the needed transparent background.
Maybe it is related to the versions of my packages. I am attaching the result of pygmt.show_versions() down below.

Versions summary

PyGMT information:
version: v0.3.0
System information:
python: 3.8.6 | packaged by conda-forge | (default, Jan 25 2021, 22:54:47) [MSC v.1916 64 bit (AMD64)]
executable: D:\Users\User\miniconda3\envs\pygmt\python.exe
machine: Windows-10-10.0.14393-SP0
Dependency information:
numpy: 1.19.5
pandas: 1.2.1
xarray: 0.16.2
netCDF4: 1.5.5.1
packaging: 20.8
ghostscript: 9.53.3
gmt: 6.1.1
GMT library information:
binary dir: D:/Users/User/miniconda3/envs/pygmt
cores: 8
grid layout: rows
library path: D:/Users/User/miniconda3/envs/pygmt/Library/bin/gmt.dll
padding: 2
plugin dir: D:/Users/User/miniconda3/envs/pygmt/Library/bin/gmt_plugins
share dir: D:/Users/User/miniconda3/envs/pygmt/Library/share/gmt
version: 6.1.1