Random Chart Generation with Altair

  • Share this:

Code introduction


This function generates a random chart based on a given dataset and chart type using the Altair library.


Technology Stack : Altair, Pandas

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import random
import altair as alt
import pandas as pd

def random_chart(data, chart_type):
    """
    Generates a random chart from a given dataset and chart type.
    """
    # Define a dictionary of available chart types and their corresponding Altair constructors
    chart_dict = {
        'bar chart': alt.Bar,
        'line chart': alt.Line,
        'scatter plot': alt.Scatter,
        'area chart': alt.Area,
        'histogram': alt.Histogram
    }
    
    # Check if the requested chart type is in the dictionary
    if chart_type not in chart_dict:
        raise ValueError(f"Unsupported chart type: {chart_type}")
    
    # Select a random color palette
    color_pal = alt.condition(
        alt.datum.color == 'red',
        alt.Color('color', palette=['red', 'blue', 'green']),
        alt.Color('color', palette=['blue', 'red', 'green'])
    )
    
    # Generate the chart
    chart = chart_dict[chart_type](data, x='x', y='y', color=color_pal)
    
    return chart

# Example usage
data = pd.DataFrame({
    'x': [1, 2, 3, 4, 5],
    'y': [2, 3, 5, 7, 11],
    'color': ['red', 'blue', 'green', 'red', 'blue']
})

# Generate a random scatter plot
scatter_chart = random_chart(data, 'scatter plot')
scatter_chart.display()                
              
Tags: