This question already has answers here:
How to put the legend out of the plot
                                
                                    (16个答案)
                                
                        
                                2年前关闭。
            
                    
图例位于图表内,有没有办法使其与水平条形图不重叠?

python - 堆叠的单杠图,图例位于图内。如何使该图更清晰可见-LMLPHP

我的数据集如下:

df=pd.DataFrame(data=([[ 0.13214286,  0.13928571,  0.16      ,  0.13285714,  0.14571429,
     0.14714286,  0.14285714],
   [ 0.11833333,  0.12666667,  0.14833333,  0.13833333,  0.145     ,
     0.17166667,  0.15166667],
   [ 0.15666667,  0.15666667,  0.14333333,  0.11333333,  0.17      ,
     0.12666667,  0.13333333],
   [ 0.13333333,  0.16166667,  0.16      ,  0.145     ,  0.14833333,
     0.12333333,  0.12833333],
   [ 0.1075    ,  0.135     ,  0.105     ,  0.1425    ,  0.1875    ,
     0.1525    ,  0.17      ],
   [ 0.13833333,  0.13888889,  0.12944444,  0.14722222,  0.16166667,
     0.14611111,  0.13833333],
   [ 0.14714286,  0.145     ,  0.12571429,  0.13      ,  0.15285714,
     0.13714286,  0.16214286],
   [ 0.147     ,  0.147     ,  0.14      ,  0.154     ,  0.132     ,
     0.139     ,  0.141     ],
   [ 0.1445    ,  0.1325    ,  0.146     ,  0.129     ,  0.147     ,
     0.143     ,  0.158     ],
   [ 0.145     ,  0.14083333,  0.14583333,  0.13666667,  0.14666667,
     0.13916667,  0.14583333],
   [ 0.12375   ,  0.1325    ,  0.14625   ,  0.14375   ,  0.1525    ,
     0.16125   ,  0.14      ],
   [ 0.142     ,  0.1545    ,  0.137     ,  0.1425    ,  0.169     ,
     0.1265    ,  0.1285    ],
   [ 0.13730769,  0.14      ,  0.15307692,  0.13961538,  0.13846154,
     0.15076923,  0.14076923]]),columns=[u'1.Fully agree', u'2.Agree', u'3.Neither agree nor disagree',
   u'4.Disagree', u'5.Strongly disagree',
   u'6.Impossible to answer: not applicable to my work',
   u'7.I prefer not to answer'],index=[u'A', u'B', u'C', u'D', u'E', u'F', u'G', u'H', u'I', u'J', u'K', u'L',
   u'M'])


我正在绘制堆叠的水平条形图:

df.plot.barh(stacked=True, edgecolor='none')
plt.legend(df.columns)
plt.legend(loc="best")

最佳答案

使用bbox_to_anchor

ax = df.plot.barh(stacked=True, edgecolor='none')

horiz_offset = 1.03
vert_offset = 1.
ax.legend(bbox_to_anchor=(horiz_offset, vert_offset))


python - 堆叠的单杠图,图例位于图内。如何使该图更清晰可见-LMLPHP

10-07 16:54