Random Chart Generator with Altair

  • Share this:

Code introduction


This function generates random charts using Altair from a provided DataFrame. It randomly selects the chart type, color, and data fields for the x and y axes.


Technology Stack : Altair (data visualization library)

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import altair as alt

def generate_random_chart(data):
    """
    Generate a random chart using Altair from provided data.
    """
    # Randomly select a type of chart to generate
    chart_type = random.choice(['bar', 'line', 'point', 'rule', 'area', 'interval', 'text'])
    
    # Randomly select a color for the chart
    color = random.choice(alt.color_scale('blueorange'))
    
    # Randomly select a field from the data to use as the x-axis
    x_field = random.choice(list(data.columns))
    
    # Randomly select a field from the data to use as the y-axis
    y_field = random.choice(list(data.columns))
    
    # Construct the chart based on the randomly selected type
    chart = alt.Chart(data).mark_point(color=color) if chart_type == 'point' else alt.Chart(data)
    chart = chart.encode(
        x=x_field,
        y=y_field,
        color=color
    ).transform_filter(
        f"{x_field} != ''"  # Filter out any NaN values in the x-axis
    )
    
    return chart

# Example usage:
# import pandas as pd
# data = pd.DataFrame({
#     'Category': ['A', 'B', 'C', 'D'],
#     'Value': [10, 20, 30, 40]
# })
# chart = generate_random_chart(data)
# print(chart)