Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
def show_bg(gobj,bgcolor=(100,200,200),**kwargs):
    """
    add new background color to a plot

    gobj         any 2D graphics object 
    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)
    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')
    """

    # make gobj transparent 
    # the first element of graphics-array has to be transparent
    # so let's draw a dummy point with option transparent=True
    D = gobj.get_minmax_data()
    gobj_t = point((D['xmin'],D['ymin']),color=bgcolor,transparent=True)   
    gobj_t += gobj

    # create temp file in DATA folder of this worksheet
    gobj_t.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')