Python matplotlib plot legend duplication
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

In the following code, the exact same image should be generated 3 times, but the legend is duplicated, then triplicated on the third image.

import matplotlib.pyplot as plt
import pandas as pd
from math import pi
def create_spider_plot(filename):  
    df = pd.DataFrame({
    'group': ['A','B','C'],
    'Applications': [3.8, 1.5, 3.0],
    'Architecture': [2.9, 1.0, 2.9],
    'Delivery':     [1.8, 2.3, 2.6],
    'Infor Mgmt':   [1.7, 2.3, 2.6],
    'Inf Sec':      [2.8, 1.5, 3.2],
    'Inf Ops':      [1.8, 2.3, 2.3],
    'S.Development': [1.8, 2.8, 3.2]
    })

    categories=list(df)[1:]
    N = len(categories)
    angles = [n / float(N) * 2 * pi for n in range(N)]
    angles += angles[:1]
   ax = plt.subplot(111, polar=True)
   ax.set_theta_offset(pi / 2)
    ax.set_theta_direction(-1) 
    plt.xticks(angles[:-1], categories)
    ax.set_rlabel_position(0)
    plt.yticks([1,2,3], ["1","2","3"], color="grey", size=7)
    plt.ylim(0,5)
    values=df.loc[0].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="Team")
    ax.fill(angles, values, 'b', alpha=0.1)
    values=df.loc[1].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="BU")
    ax.fill(angles, values, 'r', alpha=0.1)
    values=df.loc[2].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="Enter")
    ax.fill(angles, values, 'r', alpha=0.1)
    plt.rcParams.update({'font.size': 10}) #legend
    plt.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))
    fig1 = plt.gcf()
    plt.draw()
    fig1.savefig(filename, dpi=150,bbox_inches='tight')

create_spider_plot("spider1.png") # Works
create_spider_plot("spider2.png") # Legend duplicated
create_spider_plot("spider3.png") # Legend triplicated
awarded to kostasx
Tags
python3

Crowdsource coding tasks.

1 Solution

Winning solution

Add plt.clf() at the end of the function:

import matplotlib.pyplot as plt
import pandas as pd
from math import pi
def create_spider_plot(filename):  
    df = pd.DataFrame({
    'group': ['A','B','C'],
    'Applications': [3.8, 1.5, 3.0],
    'Architecture': [2.9, 1.0, 2.9],
    'Delivery':     [1.8, 2.3, 2.6],
    'Infor Mgmt':   [1.7, 2.3, 2.6],
    'Inf Sec':      [2.8, 1.5, 3.2],
    'Inf Ops':      [1.8, 2.3, 2.3],
    'S.Development': [1.8, 2.8, 3.2]
    })

    categories=list(df)[1:]
    N = len(categories)
    angles = [n / float(N) * 2 * pi for n in range(N)]
    angles += angles[:1]
    ax = plt.subplot(111, polar=True)
    ax.set_theta_offset(pi / 2)
    ax.set_theta_direction(-1) 
    plt.xticks(angles[:-1], categories)
    ax.set_rlabel_position(0)
    plt.yticks([1,2,3], ["1","2","3"], color="grey", size=7)
    plt.ylim(0,5)
    values=df.loc[0].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="Team")
    ax.fill(angles, values, 'b', alpha=0.1)
    values=df.loc[1].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="BU")
    ax.fill(angles, values, 'r', alpha=0.1)
    values=df.loc[2].drop('group').values.flatten().tolist()
    values += values[:1]
    ax.plot(angles, values, linewidth=1, linestyle='solid', label="Enter")
    ax.fill(angles, values, 'r', alpha=0.1)
    plt.rcParams.update({'font.size': 10}) #legend
    plt.legend(loc='upper right', bbox_to_anchor=(0.1, 0.1))
    fig1 = plt.gcf()
    fig1.savefig(filename, dpi=150,bbox_inches='tight')
    plt.draw()
    plt.clf() # <-- Add this

create_spider_plot("spider1.png") # Works
create_spider_plot("spider2.png") # Legend duplicated
create_spider_plot("spider3.png") # Legend triplicated

Reference

Perfect, thank you!
broadreach 5 months ago
You're welcome! Thank you .
kostasx 5 months ago