1

The legend is inside the chart, is there a way that it does not overlap with the horizontal bar plot?

bar_plot

My Data set is the following:

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'])

I am ploting a stacked horizontal bar plot:

df.plot.barh(stacked=True, edgecolor='none')
plt.legend(df.columns)
plt.legend(loc="best")
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
Nick
  • 21
  • 5
  • ax is different with plt In this case, I used plt to set legend. plt.legend(bbox_to_anchor=(0, -0.15), loc=3, prop={'size': 14}, frameon=False); – dipt Jul 25 '19 at 04:19

1 Answers1

2

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

legend outside of plot

andrew_reece
  • 20,390
  • 3
  • 33
  • 58