How to Make a Spider Chart in Python

I’ve always been fascinated by how visualizations can help us understand data better, and the Spider Chart (or Radar Chart) is one of the most dynamic ways to compare multiple attributes at once. So, I decided to create a Python program that generates Spider Charts with some practical features, including support for multiple players, dynamic input, and enhanced visualization.

The Project Overview

This project focuses on creating Spider Charts to visualize and compare data attributes across multiple players or entities. The chart is not only visually appealing but also interactive, allowing you to input player stats dynamically. Here’s a glimpse of the features I’ve added:

  1. Support for Multiple Players: Compare stats of multiple players.
  2. Dynamic Range Setting: Automatically adjust the chart’s axis range based on input data.
  3. Custom Colors: Assign unique colors to each player’s stats for better clarity.
  4. Interactive Input: Let users define players and their stats during runtime.
  5. Improved Plot Aesthetics: Add gridlines and refine overall chart appearance.

Enhanced Python Code

Here’s the complete code for the enhanced Spider Chart:

import matplotlib.pyplot as plt
import numpy as np

def create_spider_chart(categories, players_data):
    # Number of categories
    N = len(categories)

    # Create an array for the angles
    angles = [n / float(N) * 2 * np.pi for n in range(N)]
    angles += angles[:1]

    # Initialise the plot
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, polar=True)

    # Loop through each player and plot their data
    for player, data in players_data.items():
        stats = data + data[:1]  # Add the first value to close the circle
        ax.plot(angles, stats, linewidth=2, linestyle='solid', label=player)
        ax.fill(angles, stats, alpha=0.25)

    # Set the labels for each axis
    ax.set_thetagrids(np.degrees(angles[:-1]), categories)

    # Set dynamic range for each axis
    max_value = max(max(data) for data in players_data.values())
    ax.set_ylim(0, max_value + 10)

    # Add gridlines and a title
    ax.grid(True)
    plt.title('Spider Chart', size=16, weight='bold')

    # Add a legend
    plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))

    # Show the plot
    plt.show()

def get_player_data(categories):
    # Allow user to input data for multiple players
    players_data = {}
    while True:
        player_name = input("Enter player name (or type 'done' to finish): ")
        if player_name.lower() == 'done':
            break
        print(f"Enter stats for {player_name} (values separated by spaces):")
        stats = list(map(int, input().split()))
        if len(stats) != len(categories):
            print(f"Error: You must enter {len(categories)} values.")
        else:
            players_data[player_name] = stats
    return players_data

# Main program
if __name__ == "__main__":
    # Define categories
    categories = ['Speed', 'Power', 'Accuracy', 'Endurance', 'Agility']

    print("Define player stats for Spider Chart:")
    players_data = get_player_data(categories)

    if players_data:
        create_spider_chart(categories, players_data)
    else:
        print("No data provided. Exiting program.")

Features Explain

Support for Multiple Players

This program allows you to compare the stats of multiple players side by side. Each player’s stats are plotted on the same chart with a unique line and fill color.

Dynamic Range Setting

Instead of hardcoding the axis limits, the program dynamically calculates the maximum value among all players’ stats and sets the axis range accordingly. This ensures the chart always looks clean and readable.

Custom Colors

Each player’s data is displayed with a distinct color. This makes it easy to distinguish between players, especially when comparing multiple entities.

Interactive Input

You can define players and their stats during runtime. This feature makes the program flexible and reusable for different datasets without changing the code.

Improved Plot Aesthetics

Gridlines and an improved title add a professional touch to the chart. The use of alpha transparency for fills enhances readability.

Sample Run

Here’s what it looks like when you run the program:

Define player stats for Spider Chart:
Enter player name (or type 'done' to finish): Player 1
Enter stats for Player 1 (values separated by spaces):
90 75 85 80 90
Enter player name (or type 'done' to finish): Player 2
Enter stats for Player 2 (values separated by spaces):
80 90 70 85 95
Enter player name (or type 'done' to finish): done

The program generates a Spider Chart that compares the stats of Player 1 and Player 2. Each player’s stats are represented by a distinct line and shaded area.

Why This Project Matters

This Spider Chart tool is versatile and practical for many use cases, such as:

  • Comparing team performance metrics.
  • Visualizing attributes of game characters.
  • Analyzing data for business or educational purposes.

With its enhanced features and user-friendly design, this program is a great way to practice Python and create a valuable visualization tool.

Conclusion

Creating this enhanced Spider Chart program was an exciting journey. It’s a fantastic example of how Python’s libraries like Matplotlib can turn data into compelling visuals. Whether you’re a beginner or an experienced programmer, this project is a fun and educational way to improve your coding and visualization skills.

Related blog posts