4

I am using Matplotlib and Seaborn for some plotting purposes. I want plots that have a transparent background instead of a black-background. My code is

plt.style.use("dark_background")
plt.figure(figsize=(15,8))
sns.swarmplot(x='type',y='value', data=df, size=3.5, color='r', alpha=0.4)
sns.boxplot(x='type',y='value',data=df)

and the plot is enter image description here

Now is there any style or technique using which I can have same background color of plot which I have for my cell, i.e background of my plot is Transparent.

Thanks

Ahmad Anis
  • 2,322
  • 4
  • 25
  • 54
  • Does this answer your question? [How to set opacity of background colour of graph wit Matplotlib](https://stackoverflow.com/questions/4581504/how-to-set-opacity-of-background-colour-of-graph-wit-matplotlib) – JE_Muc Jul 27 '20 at 11:21
  • This is for saving figures. I want it to be transparent in cell. – Ahmad Anis Jul 27 '20 at 11:25
  • Not exclusively. Did you take a look at the [second answer](https://stackoverflow.com/a/62466259/6345518)? This sets the background globally, which seems like a good solution for your case, since you are writing of "some plotting purposes". – JE_Muc Jul 27 '20 at 11:29

1 Answers1

9

If you just want the entire background for both the figure and the axes to be transparent, you can simply specify transparent=True when saving the figure with fig.savefig.

e.g.:

import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', transparent=True)

If you want more fine-grained control, you can simply set the facecolor and/or alpha values for the figure and axes background patch. (To make a patch completely transparent, we can either set the alpha to 0, or set the facecolor to 'none' (as a string, not the object None!))

e.g.:

import matplotlib.pyplot as plt
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.patch.set_facecolor('red')
ax.patch.set_alpha(0.5)
# If we don't specify the edgecolor and facecolor for the figure when
# saving with savefig, it will override the value we set earlier!
fig.savefig('temp.png', facecolor=fig.get_facecolor(), edgecolor='none')
plt.show()
Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
  • If the OP want to place their figure over a pre-existent, darkish image they could simply reduce the opacity of the figure/axes so that the light colored graphical elements stand out over the _slightly darker_ part of the pre-existent image. – gboffi Jul 27 '20 at 12:11
  • Nice answer, I especially appreciated the comment about `fig.savefig` – gboffi Jul 27 '20 at 12:12