Randomly Generated Charts with Altair

  • Share this:

Code introduction


This code defines a function named `generate_random_chart` that randomly selects a chart type (bar, line, area, scatter, pie) and generates the corresponding chart using the Altair library. It first loads car data from the Vega dataset, then creates a basic encoding, and finally generates the chart based on the selected chart type.


Technology Stack : The packages and technologies used in this code include: Altair, Pandas, and Vega datasets.

Code Type : Function

Code Difficulty :


                
                    
import random
import altair as alt
import pandas as pd
from vega_datasets import data

def generate_random_chart():
    # Randomly select a type of chart to generate
    chart_type = random.choice(['bar', 'line', 'area', 'scatter', 'pie'])
    
    # Generate a random dataset
    df = data.cars()
    
    # Create a base encoding for all charts
    base_encoding = alt.Chart(df).encode(
        x=alt.X('Horsepower:Q', title='Horsepower'),
        y=alt.Y('Miles_per_Gallon:Q', title='Miles per Gallon')
    )
    
    # Generate the chart based on the selected type
    if chart_type == 'bar':
        chart = base_encoding.mark_bar()
    elif chart_type == 'line':
        chart = base_encoding.mark_line()
    elif chart_type == 'area':
        chart = base_encoding.mark_area()
    elif chart_type == 'scatter':
        chart = base_encoding.mark_point()
    elif chart_type == 'pie':
        chart = base_encoding.mark_circle().encode(
            alt.Color('Origin:N', title='Origin')
        )
    
    return chart

# Output the chart
chart = generate_random_chart()
print(chart)