Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Using PIL offers a further way. PIL is included in Sage.

def show_bg(gobj,bgcolor=(100,200,200),**kwargs):
    """
    add background color to a transparent plot

    gobj         any 2D graphics object created with option transparent=True
    bgcolor      tuple  (r,g,b) r,g,b in range 0..255
                 or string with proper color name 
    kwargs       all other keyword args are passed to save    

    EXAMPLES:
    sage: P = plot(sin,-pi,pi,color='red',thickness=2,transparent=True)
    sage: P += parametric_plot((2*x,x),(x,-2,2),color='gold',thickness=3)
    sage: show_bg(P,aspect_ratio=3/2,figsize=5,bgcolor='mistyrose')

    """

    # create temp file in DATA folder of this worksheet
    gobj.save(DATA+'tmp_plot.png',**kwargs)

    from PIL import Image
    im = Image.open('./data/tmp_plot.png')

    # create background file of same size and given bgcolor    
    bg = Image.new('RGB',im.size,bgcolor)

    # paste im into bg using im as mask
    bg.paste(im,(0,0),im)
    bg.save('output.png')