简体   繁体   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

在此处输入图片说明

Howdy, so I'm using matplotlib to plot and I wrote a function to do the plotting that I call 3 times.你好,所以我使用 matplotlib 进行绘图,并编写了一个函数来执行我调用 3 次的绘图。 In the function I plt.clf() before I plot, I then save the result as a pdf, then I do plt.clf() again.在绘图之前的函数 I plt.clf() 中,然后将结果保存为 pdf,然后再次执行 plt.clf()。 I would assume doing this would guarantee that all these pictures should be the same size/centered at the same spot, but as you can see they are not.我认为这样做可以保证所有这些图片的大小应该相同/居中在同一个位置,但正如你所看到的,它们不是。 I attached my function - some insight to make sure all plots are uniformly the same dimensions when put next to eachother is what I'm aiming for.我附上了我的功能 - 一些洞察力,以确保所有的图在彼此相邻时都具有相同的尺寸,这就是我的目标。

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()

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

The issue I guess is I didn't both define a fixed height/width and also setting the dpi correctly.我猜的问题是我没有定义固定的高度/宽度,也没有正确设置 dpi。 Works great on my side after I did what this poster suggested.在我做了这张海报建议的事情后,我这边效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM