Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Remove borders from charts and legend

I have the following plot:

dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in 
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1))

Which displays this:

enter image description here

I want to remove all of the borders of the chart and legend i.e. the box around the chart (leaving the axis numbers like 2015 and 6000 etc)

All of the examples I find refer to spines and 'ax', however I have not built my chart using fig = plt.figure() etc.

Anyone know how to do it?

like image 257
ScoutEU Avatar asked Apr 25 '18 10:04

ScoutEU


1 Answers

You can remove the border of the legend by using the argument frameon=False in the call to plt.legend().

If you only have one figure and axes active, then you can use plt.gca() to get the current axes. Alternatively df.plot.bar returns an axes object (which I would suggest using because plt.gca() might get confusing when working with multiple figures). Therefore you can set the visibility of the spines to False:

ax = dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in 
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1), frameon=False)

for spine in ax.spines:
    ax.spines[spine].set_visible(False)

    # Color of the spines can also be set to none, suggested in the comments by ScoutEU 
    # ax.spines[spine].set_color("None")
like image 111
DavidG Avatar answered Oct 03 '22 20:10

DavidG