Understanding of the bbox_to_anchor parameter in the pie chart plt.pie() and plt.legend() of matplotlib visualization

  • Function function: Indicates the proportion of discrete variables
  • 调用方法:plt.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False)
  • Parameter Description:
    • x: specifies the data for plotting
    • explode: Specifies the highlighting of certain parts of the pie chart, that is, an explosion
    • labels: Add label descriptions for pie charts, similar to legend descriptions
    • colors: Specify the fill color of the pie chart
    • autopct: Automatically add percentage display, which can be displayed in a formatted way
    • pctdistance: Set the distance between the percentage label and the center of the circle
    • shadow: Whether to add the shadow effect of the pie chart
    • labeldistance: Set the distance between each sector label (legend) and the center of the circle;
    • startangle: set the initial placement angle of the pie chart;
    • radius: set the radius of the pie chart;
    • counterclock: Whether to make the pie chart appear in counterclockwise order;
    • wedgeprops: Set the properties of the inner and outer boundaries of the pie chart, such as the thickness and color of the boundary line;
    • textprops: Set the properties of the text in the pie chart, such as font size, color, etc.;
    • center: Specify the center point position of the pie chart, the default is the origin
    • frame: Whether to display the frame behind the pie chart, if set to True, you need to control the range of the x-axis and y-axis of the frame and the center position of the pie chart at the same time;

1. Draw a simple pie chart:

2. Ring chart: draw by parameter wedgecolor = {'width':0.5}, and the custom value 0.5 represents the width of the ring chart

 3. Draw a complex pie chart with multiple parameters:

#构造数据:某城镇受教育程度
education = [9823, 5601, 3759, 1400, 450]
labels = ['小学', '初中', '高中', '大学', '研究生及以上']

explode = [0,0,0,0.2,0.3]  # 用于突出显示特定人群
# 自定义颜色,更多颜色参考颜色网站:https://xkcd.com/color/rgb/
colors=['#9999ff','#ff9999','#7777aa','#2442aa','#dd5555'] 

# 将横、纵坐标轴标准化处理,保证饼图是一个正圆,否则可能为椭圆
plt.axes(aspect='equal')

# 绘制饼图
plt.pie(x = education,         # 绘图数据        
        explode=explode,       # 突出显示特定人群
        labels=labels,         # 添加教育水平标签
        colors=colors,         # 设置饼图的自定义填充色
        autopct='%.1f%%',      # 设置百分比的格式,这里保留一位小数
        pctdistance=0.7,       # 设置百分比标签与圆心的距离
        labeldistance = 1.15,  # 设置教育水平标签与圆心的距离
        startangle = 180,      # 设置饼图的初始角度
        radius = 1.5,          # 设置饼图的半径
        counterclock = False, # 是否逆时针,这里设置为顺时针方向
        # 设置饼图内外边界的属性值:linewidth表示饼图内外边框线宽度;width表示饼图内外宽度,可控制生成环形图;edgecolor表示边框线的颜色        
        wedgeprops = {'linewidth': 1.5,'width':0.5, 'edgecolor':'green'},  
        textprops = {'fontsize':12, 'color':'k'},   # 设置文本标签的属性值
        center = (0,0),        # 设置饼图的原点
        frame = 0)             # 是否显示饼图的图框,这里设置不显示



# 显示图形
plt.show()

4. Embedded ring chart: used to analyze the comparison of two groups of data with the same category

Draw by setting wedgeprops={'width':num} with the radius radius and the width of the ring chart

Example: Analyzing the proportion of ingredients in two strawberry cakes

# 自定义颜色图列表
colormaplist = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"]
elements =['面粉','糖','奶油','草莓','坚果']
weight1 = [40,15,20,10,15]
weight2 = [30,25,15,20,10]

plt.pie(weight1,
        autopct="%3.1f%%",           # 百分比显示格式
        radius=1,                    # 半径
        pctdistance=0.85,            # 百分比文本距离圆心距离
        colors=colormaplist,         # 颜色
        textprops=dict(color= "w"),  # 文本设置 
        labels = elements,           # 各类别标签
        wedgeprops=dict(width=0.3, edgecolor = 'w'))  # 饼图内外边格式设置

plt.pie(weight2,
        autopct="%3.1f%%",
        radius=0.7,
        pctdistance=0.75,
        colors=colormaplist, #内环形图也使用相同的颜色图,否则会出现同类别的两个数据颜色不对应,不利于观测分析
        textprops=dict(color= "w"),
        wedgeprops=dict(width=0.3, edgecolor = 'w'))

# 通过legend函数中的loc和bbox_to_anchor参数控制图例位置
# bbox_to_anchor = (x,y,width,height)具体四个参数含义在后面解释
plt.legend( loc = 'center right',bbox_to_anchor = (1.15,0,0.3,1),fontsize = 15)
plt.title('两种草莓蛋糕中配料的比例对比图',fontsize = 17)

plt.show()

5. The understanding of the four parameters in bbox_to_anchor = (x, y, width, height) in plt.legend()

 1) The bbox_to_anchor  parameter is used to better control and adjust the position of the legend box

 2) x, y represent the coordinate position of a certain point of the legend frame, and as for where that point is, it depends on the parameter loc in plt.legend, for example: loc = 'center', then x, y represents the center point of the legend frame s position;

3) width indicates how much distance the initial position of the original legend frame represented by x, y is moved horizontally (from the width of the original legend frame);

  height indicates how much the initial position of the original legend box represented by x and y is moved vertically (the height from the original legend box);

The following is used as a diagram to understand:

fig,ax = plt.subplots(2,1,figsize = (8,5))

ax[0].scatter(0.5,0.5,label = '(0.5,0.5,0,0)')
ax[0].legend(loc = 'upper right',bbox_to_anchor = (0.5,0.5,0,0),prop={'size':20})
ax[0].set_xlim(0,1)
ax[0].set_ylim(0,1)


ax[1].scatter(0.5,0.5,label = '(0.5,0.5,0.5,0.5)')
ax[1].legend(loc = 'upper right',bbox_to_anchor = (0.5,0.5,0.5,0.5),prop={'size':20})
ax[1].set_xlim(0,1)
ax[1].set_ylim(0,1)


plt.subplots_adjust(hspace=0.2)
plt.show()

 It can be seen from the first sub-figure above that: the upper right vertex ('upper right') of the legend box corresponds to the point (0.5,0.5); from the second sub-figure, it can be seen that when the width and height are set to 0.5, it means the distance of the new legend box The position of the original legend box is at a horizontal and vertical distance of 0.5, and the position of the upper right vertex of the new legend box is (1,1).
 

Guess you like

Origin blog.csdn.net/weixin_46707493/article/details/119837887