Random Chart Generation with Altair

  • Share this:

Code introduction


This function generates a random chart using the Altair library based on the provided DataFrame. It randomly selects the chart type, color, marker, and scale type.


Technology Stack : Altair library, Pandas DataFrame, random selection, chart generation

Code Type : The type of code

Code Difficulty : Advanced


                
                    
import random
import altair as alt

def generate_random_chart(data):
    """
    This function generates a random chart using Altair based on the provided data.
    """
    # Generate a random number of marks to include in the chart
    num_marks = random.randint(1, 10)
    # Randomly select a mark type
    mark_type = random.choice(['circle', 'square', 'triangle', 'cross', 'x', 'diamond', 'plus', 'asterisk', 'none'])
    # Randomly select a color
    color = random.choice(alt.colorbrewer.colors('Set1', 5))
    # Generate a random scale type
    scale_type = random.choice(['linear', 'log', 'sqrt'])
    # Generate a random field to use for the chart
    field = random.choice(data.columns)
    # Create the chart
    chart = alt.Chart(data).mark_point(color=color).encode(
        alt.X(field, scale=alt.Scale(type=scale_type)),
        alt.Y('count(*)', bin=alt.Bin(maxbins=num_marks))
    )
    return chart

# Example usage:
# Assuming 'df' is a pandas DataFrame with at least one column
# chart = generate_random_chart(df)
# chart.display()