Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to colour the outer ring (like a doughnut plot) in a radar plot according to column values

I have data in this form :

data = {'Letter': ['A', 'B', 'C', 'D', 'E'],
        'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'],
        'Value': [1, 2, 0, 5, 6]}

df = pd.DataFrame(data)


I want to combine a doughnut plot and a radar plot, where the outer ring will be coloured according to the column "Type".

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

data = {'Letter': ['A', 'B', 'C', 'D', 'E'],
        'Type': ['Apples', 'Apples', 'Oranges', 'Oranges', 'Bananas'],
        'Value': [1, 2, 0, 5, 6]}

df = pd.DataFrame(data)


num_categories = len(df)


angles = np.linspace(0, 2 * np.pi, num_categories, endpoint=False).tolist()


values = df['Value'].tolist()
values += values[:1]
angles += angles[:1]


plt.figure(figsize=(8, 8))
plt.polar(angles, values, marker='o', linestyle='-', linewidth=2)


plt.fill(angles, values, alpha=0.25)

plt.xticks(angles[:-1], df['Letter'])


types = df['Type'].unique()
color_map = {t: i / len(types) for i, t in enumerate(types)}

colors = df['Type'].map(color_map)
plt.fill(angles, values, color=plt.cm.viridis(colors), alpha=0.25)

plt.show()


I want this to look like this : enter image description here

like image 655
zorals Avatar asked Nov 02 '25 19:11

zorals


1 Answers

You could use Wedge:

from matplotlib.patches import Wedge
from matplotlib import colormaps

ax = plt.gca()
cmap = plt.cm.viridis.resampled(df['Type'].nunique())

# group consecutive types
g = df['Type'].ne(df['Type'].shift()).cumsum()

# set up colors per type
colors = dict(zip(df['Type'].unique(),
                  map(matplotlib.colors.to_hex, cmap.colors)))
# {'Apples': '#440154', 'Oranges': '#21918c', 'Bananas': '#fde725'}

# radius of wedge
y = 0.49

# loop over groups
for (_, name), grp in df.reset_index(drop=True).groupby([g, 'Type']):
    factor = 360/len(df)
    start = (grp.index[0]-0.5)*factor
    end = (grp.index[-1]+0.5)*factor
    ax.add_artist(Wedge((0.5, 0.5), y, start, end, width=0.01,
                        color=colors[name], transform=ax.transAxes)
                 )

Output:

enter image description here

like image 191
mozway Avatar answered Nov 04 '25 09:11

mozway