0

In bokeh's document, it said to create png with transparent background, one should set:

plot.background_fill_color = None
plot.border_fill_color = None

But since internally, they're saving png file by calling:

png = web_driver.get_screenshot_as_png()

and the saved screenshot is always has white background, so I can not find a way to save png with transparent backgound. please let me know what I did wrong.

TMS
  • 363
  • 5
  • 17
  • this method worked for me as a temporary solution (the second method): https://stackoverflow.com/a/46755537/884553 – TMS Jun 16 '23 at 07:29

1 Answers1

0

This is also a workaround with the PIL package.

I found this post with a solution for transforming white pixel into transparend. But be careful, with this approach you will lose all valid white pixel.

from bokeh.plotting import figure
from bokeh.io import show, output_notebook, export_png
from bokeh.themes import Theme
output_notebook()

p = figure(width=500, height=250)
p.line(x=[1,2,3,4,5,6,7], y=[0,1,2,5,4,3,1], color='white')
p.background_fill_color = None
p.border_fill_color = None
export_png(p, filename="plot.png")

from PIL import Image
img = Image.open('plot.png')
img = img.convert("RGBA")

pixdata = img.load()

width, height = img.size
for y in range(height):
    for x in range(width):
        if pixdata[x, y] == (255, 255, 255, 255):
            pixdata[x, y] = (255, 255, 255, 0)

img.save("plot_transparend.png", "PNG")

This is plot_transparend.png opened in paint.net.

result in opened in paint.net

A other option is to save a svg file using export_svg and trasfrom this into a png file.

mosc9575
  • 5,618
  • 2
  • 9
  • 32