【问题标题】:How to stop multiple subplots overlapping in mathplotlib?如何停止 matplotlib 中重叠的多个子图?
【发布时间】:2021-05-18 02:56:19
【问题描述】:

我想并排显示两个饼图,也就是甜甜圈图。但是使用下面的代码,我得到的只是重叠图。我尝试使用各种值进行子图调整,但图例总是重叠。把函数中所有不相关的代码都剪掉了

#Function to draw graphs for sports data
        
    #Create figure with two subplots
    fig,ax=plt.subplots(1,2,subplot_kw=dict(aspect="equal"))
    j=0
    
    #Loop through all columns we want to graph
    for type in types:
                  
        #Create a pie chart
        wedges, texts, autotexts = ax[j].pie(to_plot,         
                explode=explode,  
                labels=labels,     
                colors=colors,      
                autopct=lambda pct: func(pct, data), 
                pctdistance=0.8,    
                counterclock=False, 
                startangle=90,      
                wedgeprops={'width': 0.75}, 
                radius=1.75       
                )

        #Set label colors
        for text in texts:
            text.set_color('grey')

        #Create legend
        ax[j].legend(wedges, leg_labels,
            title=title,
            title_fontsize="x-large",
            loc="center left",
            bbox_to_anchor=(1.5, 0, 0.5, 1),
            prop={'size': 12})

        j += 1
    
    plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.5, hspace=None)
    plt.show()
    return

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    确定图例位置的 bbox 设置设置在每个饼图的右侧,因此它们重叠。因此,我们可以通过设置图表各自的位置来避免图例重叠。

    import matplotlib.pyplot as plt
    
    # Some data
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15, 30, 45, 10]
    titles = ['20 members\nfollow Basketball','23 members\nfollow Basketball']
    legend_pos = ['center left','center right']
    bboxes = [(-1.0, 0, 0.5, 1),(1.5, 0, 0.5, 1)]
    # Make figure and axes
    fig, axs = plt.subplots(1, 2, subplot_kw=dict(aspect="equal"))
    
    for i in range(2):
        wedges, texts,_ = axs[i].pie(fracs,
                                     labels=labels,
                                     autopct='%.0f%%',
                                     shadow=True,
                                     explode=(0, 0.1, 0, 0),
                                     wedgeprops=dict(width=0.6))
        
        axs[i].legend(wedges,
                     labels,
                     title=titles[i],
                     title_fontsize="x-large",
                     loc=legend_pos[i],
                     bbox_to_anchor=bboxes[i],
                     prop={'size': 12})
        
    plt.show()
    

    【讨论】:

    • 本示例是对官方参考示例的自定义回复。如果我的回答对你有帮助,请考虑采纳为正确答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2013-01-08
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多