Making figure transparent with colored background

后端 未结 3 1976
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 18:09

I have a bit of a situation. What I need is a plot with a black background with several white circles drawn on top of that black background.

I managed to do this usi

3条回答
  •  梦谈多话
    2021-01-12 18:50

    This might not be the answer you are looking for but it gives the picture you wanted! I think you want to fill the areas outside the circle!(s) with black and leave the background transparent, rather than the other way around. It's trivial to calculate the boundaries of a single circle and use fill_between. Doing it for multiple circles might be trickier!

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1, aspect = "equal", )
    
    # A Circle
    xy=(1,1); r=3
    
    # more points is smoother
    xdata=np.linspace(-5,5,1001)
    ydata=np.linspace(-5,5,1001)
    
    # circle edges (top and bottom)
    c1=np.sqrt((xy[0]**2-xdata**2)+r**2)+xy[1]
    c2=-np.sqrt((xy[0]**2-xdata**2)+r**2)+xy[1]
    
    c1=np.where(np.isnan(c1),xy[0],c1)
    c2=np.where(np.isnan(c2),xy[0],c2)
    
    ax.fill_between(xdata,5,c1,color='black')
    ax.fill_between(xdata,-5,c2,color='black')
    
    plt.xlim(-5, 5)
    plt.ylim(-5, 5)
    
    fig.savefig("test.png", dpi = 300, transparent=True)
    

    Transparent circle with center 1,1 and radius 3

提交回复
热议问题