To save the figure with a transparent background for use in Inkscape, modify the plt.savefig() call by adding the transparent=True parameter. Here's how to adjust your code:
Modified Code:
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import cmr # Assuming 'cmr' is already imported/imported correctly
n = 100
theta = np.linspace(0, 2 * np.pi, n)
radial = np.linspace(0, 1, 2)
_, mesh = np.meshgrid(radial, theta)
figsize = 1
fig = plt.figure(figsize=(figsize, figsize), dpi=200)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection='polar')
cmapper2 = cmr.copper_s
ax.pcolormesh(theta, radial, mesh.T,
norm=mpl.colors.Normalize(0, 2 * np.pi),
cmap=cmapper2)
ax.set_thetagrids(
np.linspace(0, 360, 4, endpoint=False),
[r"$0$", r"$\frac{\pi}{2}$", r"$\pi$", r"$\frac{3\pi}{2}$"]
)
ax.set_yticklabels([])
ax.xaxis.grid(True, alpha=0.3)
ax.yaxis.grid(True, alpha=0.3)
# Set transparent background
plt.savefig("polarity.png",
bbox_inches='tight',
transparent=True) # Add this parameter
Key Changes:
transparent=True in plt.savefig() ensures the background is transparent.
- The
bbox_inches='tight' parameter remains to crop whitespace around the plot.
Optional: Ensure Full Transparency (if needed)
If the background still appears white, explicitly set the figure and axes backgrounds to transparent:
# Before plotting:
fig = plt.figure(figsize=(figsize, figsize), dpi=200, facecolor='none') # Set figure facecolor to transparent
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection='polar', facecolor='none') # Set axes facecolor to transparent
# ... (rest of your code) ...
# After plotting:
plt.savefig("polarity.png",
bbox_inches='tight',
transparent=True,
pad_inches=0) # Remove padding around the plot
Notes:
transparent=True overrides the default white background.
facecolor='none' removes the figure/axes backgrounds entirely.
pad_inches=0 ensures no extra padding is added during saving.
This will produce a PNG with a transparent background, ready for editing in Inkscape! 🖼️