Home > Software engineering >  legend color spyder plot python
legend color spyder plot python

Time:03-01

From the following sample dataset:

df_toy = pd.DataFrame({"Group":[1,2],
                   "Var1":[100,20],
                   "Var2":[50,40],
                   "Var3":[10,14],
                   "Var4":[10,140],
                   "Var5":[100,14]})

I am plotting a spyder/polar plot by means of the following code:

variables = [col for col in df_toy.columns if col != "Group"]
labels= variables   [variables[0]]

np.random.seed(1)
angles = np.linspace(0, 2 * np.pi, len(variables), endpoint=False)

# The first value is repeated to close the chart.
angles=np.concatenate((angles, [angles[0]]))

# polar plot each row separately
for row in df_toy.values.tolist():
    values = row[1:]   [row[1]]
    plt.polar(angles, values, 'o-', linewidth=2)
    plt.fill(angles, values, alpha=0.25)

# Representation of the spider graph
plt.legend(df_toy["Group"])
plt.thetagrids(angles * 180 / np.pi, labels)
plt.show()

which produces the following plot, However, there is a wrong correspondence between legend and line color:

enter image description here

what I am doing wrong?

CodePudding user response:

Label the legend entries while plotting:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
...
...
# polar plot each row separately
for row in df_toy.values.tolist():
    values = row[1:]   [row[1]]
    plt.polar(angles, values, 'o-', linewidth=2, label=row[0])
    plt.fill(angles, values, alpha=0.25)

# Representation of the spider graph
plt.legend()
...

Sample output:

enter image description here

CodePudding user response:

I don't reproduce your issue:

import matplotlib.pyplot as plt

df_toy = pd.DataFrame({"Group":[1,2],
                   "Var1":[100,20],
                   "Var2":[50,40],
                   "Var3":[10,14],
                   "Var4":[10,140],
                   "Var5":[100,14]})

variables = [col for col in df_toy.columns if col != "Group"]
labels= variables   [variables[0]]

np.random.seed(1)
angles = np.linspace(0, 2 * np.pi, len(variables), endpoint=False)

# The first value is repeated to close the chart.
angles=np.concatenate((angles, [angles[0]]))

# polar plot each row separately
for row in df_toy.values.tolist():
    values = row[1:]   [row[1]]
    plt.polar(angles, values, 'o-', linewidth=2)
    plt.fill(angles, values, alpha=0.25)

# Representation of the spider graph
plt.legend(df_toy["Group"])
plt.thetagrids(angles * 180 / np.pi, labels)
plt.show()

output:

polar plot

  • Related