簡體   English   中英

pylab matplotlib 多次調用帶有 clf() 和 savefig as pdf 的繪圖函數生成不同大小/居中的繪圖

[英]pylab matplotlib multiple calls of a plot function with clf() and savefig as pdf produces plots of different sizes/centering

在此處輸入圖片說明

你好,所以我使用 matplotlib 進行繪圖,並編寫了一個函數來執行我調用 3 次的繪圖。 在繪圖之前的函數 I plt.clf() 中,然后將結果保存為 pdf,然后再次執行 plt.clf()。 我認為這樣做可以保證所有這些圖片的大小應該相同/居中在同一個位置,但正如你所看到的,它們不是。 我附上了我的功能 - 一些洞察力,以確保所有的圖在彼此相鄰時都具有相同的尺寸,這就是我的目標。

def plot_example(material_list,v_list,domain_number,color_list,number_of_squares,title):
    left = Left()
    top = Top()
    right = Right()
    bottom = Bottom()
    obstacle = Obstacle()
    obstacletwo = Obstacletwo()
    obstaclethree = Obstaclethree()
    obstaclefour= ObstacleFour()
    circle = Circle()
    rho_val=.75
    # directions = [(1.0,0),(0,1.0),(1.0/math.sqrt(2),1.0/math.sqrt(2))]
    # weights = [.25,.25,.5]
    track_sols=False
    p1 = Point(-1.0,-1.0)
    p2 = Point(1.0,1.0)
    mesh = RectangleMesh(p1,p2,128,128)
    element = VectorElement('CG', triangle, 1, dim=2)
    V = FunctionSpace(mesh, element)
    objfunc=FunctionSpace(mesh, "CG", 1)
    dg = FunctionSpace(mesh,'DG',0)

    domains = MeshFunction("size_t", mesh,mesh.topology().dim())
    domains.set_all(0)

    # cc=CellFunction("bool",mesh,False)
    # circle.mark(cc,True)
    # mesh=refine(mesh,cc)

    obstacle.mark(domains, 1)
    obstacletwo.mark(domains, 2)
    obstaclethree.mark(domains, 3)
    obstaclefour.mark(domains,4)
    circle.mark(domains,5)
    # v = File("mesh.pvd")
    # v << mesh


    boundaries = MeshFunction("size_t", mesh,mesh.topology().dim()-1)
    boundaries.set_all(0)
    left.mark(boundaries, 1)
    top.mark(boundaries, 2)
    right.mark(boundaries, 3)
    bottom.mark(boundaries, 4)

    dx = Measure("dx")(subdomain_data=domains)
    ds = Measure("ds")(subdomain_data=boundaries)

    print("building squares")
    relax_obj=None
    square_list=[]
    counter=0
    square_matrix=[]
    x_list = np.linspace(-(5.0/8.0),(5.0/8.0),number_of_squares+1)
    y_list = np.linspace((5.0/8.0),-(5.0/8.0),number_of_squares+1)
    h = x_list[1]-x_list[0]
    for j in range(0,len(y_list)-1):
        #square_matrix.append([])
        for i in range(0,len(x_list)-1):
            point = (x_list[i] + (h/2.0),y_list[j] - (h/2.0))
            curr = square_class(point,h,counter)
            counter+=1
            square_list.append(curr)
            #square_matrix[j].append(curr)
    index_cells=domains.where_equal(1)
    for index in index_cells:
        index_dof=dg.dofmap().cell_dofs(index)[0]
        cell = Cell(mesh,index)
        cell_midpoint = (cell.midpoint().x(),cell.midpoint().y())
    #   pos_x = math.floor(cell_midpoint[0]/h)
    #   pos_y=math.floor(cell_midpoint[1]/h)
    #   square_up = square_matrix[pos_y][pos_x]
    #   square_up.element_in_sqare(index_dof)


    # for row in square_matrix:
    #   for entry in row:
    #       square_list.append(entry)

        for square in square_list:
            if (square.point_in_square(cell_midpoint)):
                square.element_in_sqare(index_dof)
                break
    def_counter=0
    num_mat= len(material_list)
    total_ele = (number_of_squares**2)*num_mat

    for k in range(0,len(square_list)):
        #print(len(square_list))
        curr_list = v_list[k*num_mat:k*num_mat+num_mat]
        #print((k*num_mat,k*num_mat + num_mat))
        square = square_list[k]
        square.square_val = sum(curr_list)
        q_elee = None

        for j in range(0,num_mat):
            if(curr_list[j]==1):
                q_elee=j+1
                #print(q_elee)
                break
            elif(j == len(curr_list)-1):
                q_elee=0
        #print((curr_list,q_elee))
        square.q_ele = q_elee
        #print(square.q_ele)
        if(q_elee>0):
            square.q_val = material_list[q_elee-1]
        else:
            square.q_val = 0





    w=Function(dg)
    w_temp = w.vector().get_local() 
    number_list=[]
    number_list.append(0)
    for i in range(0,len(square_list)):
        cur_square = square_list[i]
        if(cur_square.q_ele in number_list or cur_square.q_ele==0):
            pass

        else:
            #print(cur_square.q_ele)
            number_list.append(cur_square.q_ele)

        #cur_square.square_val=random.randint(0,1)
        #cur_square.square_val = random.randint(0,1)
        #print(cur_square.q_ele)
        for ele in cur_square.index_list:
            #print(cur_square.q_ele)
            w_temp[ele] = cur_square.q_ele
    w.vector().set_local(w_temp)
    number_list.sort()
    my_color_map =[]
    my_color_map.append('b')
    # print(number_list)
    for k in range(1,len(number_list)):
        # print(color_list[number_list[k]])
        my_color_map.append(color_list[number_list[k]])

    val_list = []
    for i in range(0,len(number_list)):
        val_list.append(i)

    for k in range(0,len(square_list)):
        #print(len(square_list))
        curr_list = v_list[k*num_mat:k*num_mat+num_mat]
        #print((k*num_mat,k*num_mat + num_mat))
        square = square_list[k]
        square.square_val = sum(curr_list)
        q_elee = None

        for j in range(0,num_mat):
            if(curr_list[j]==1):
                index_lol = j+1
                # print("lols")
                # print(curr_list)
                # print("fdsf")
                # print(j+1)
                q_elee=number_list.index(index_lol)
                #print(q_elee)
                # print(number_list)
                # print(val_list)
                break
            elif(j == len(curr_list)-1):
                q_elee=0
        #print((curr_list,q_elee))
        square.q_ele = q_elee
        #print(square.q_ele)
        if(q_elee>0):
            square.q_val = material_list[q_elee-1]
        else:
            square.q_val = 0

    w=Function(dg)
    w_temp = w.vector().get_local() 
    number_list=[]
    number_list.append(0)
    for i in range(0,len(square_list)):
        cur_square = square_list[i]
        #print(cur_square.q_ele)
        if(cur_square.q_ele in number_list or cur_square.q_ele==0):
            pass

        else:
            number_list.append(cur_square.q_ele)

            #cur_square.square_val=random.randint(0,1)
            #cur_square.square_val = random.randint(0,1)
            #print(cur_square.q_ele)
        for ele in cur_square.index_list:
            #print(cur_square.q_ele)
            w_temp[ele] = cur_square.q_ele
    w.vector().set_local(w_temp)



    cmap = colors.ListedColormap(my_color_map)
    print(color_list[0:len(material_list)+1])
    print(my_color_map)
    print(number_list)
    plt.clf()
    plot(w,cmap=cmap)
    if(domain_number==3):
        plt.gca().add_patch(matplotlib.patches.Rectangle((-5.0/8.0,-5.0/8.0),1.25,1.25,color='black',fill=False))
        plt.gca().add_patch(matplotlib.patches.Rectangle((-.6,.7),1.2,.3,color='black',fill=False))
        #plt.gca().add_patch(matplotlib.patches.Rectangle((.7,.7),.3,.3,color='black',fill=False))
        #circle1 = plt.Circle((.85, .85), 0.1, fill=False, color='black')
        #plt.gcf().gca().add_artist(circle1)
    if(domain_number==4):
        plt.gca().add_patch(matplotlib.patches.Rectangle((-5.0/8.0,-5.0/8.0),1.25,1.25,color='black',fill=False))
        #plt.gca().add_patch(matplotlib.patches.Rectangle((-.6,.7),1.2,.3,color='black',fill=False))
        plt.gca().add_patch(matplotlib.patches.Rectangle((.7,.7),.3,.3,color='black',fill=False))
        # circle1 = plt.Circle((.85, .85), 0.1, fill=False, color='black')
        # plt.gcf().gca().add_artist(circle1)
    if(domain_number==5):
        plt.gca().add_patch(matplotlib.patches.Rectangle((-5.0/8.0,-5.0/8.0),1.25,1.25,color='black',fill=False))
        #plt.gca().add_patch(matplotlib.patches.Rectangle((-.6,.7),1.2,.3,color='black',fill=False))
        #plt.gca().add_patch(matplotlib.patches.Rectangle((.7,.7),.3,.3,color='black',fill=False))
        circle1 = plt.Circle((.85, .85), 0.1, fill=False, color='black')
        plt.gcf().gca().add_artist(circle1)

    plt.xlim(-1.0,1.0)
    plt.ylim(-1.0,1.0)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.savefig(title)
    plt.clf()

https://stackoverflow.com/a/44161399/3511656

我猜的問題是我沒有定義固定的高度/寬度,也沒有正確設置 dpi。 在我做了這張海報建議的事情后,我這邊效果很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM