Random Chart Generation with Altair

  • Share this:

Code introduction


This code defines a function that randomly generates different types of charts using the Altair library and randomly selects colors to fill the charts.


Technology Stack : Altair library, random chart generation, color palette

Code Type : The type of code

Code Difficulty :


                
                    
import random
import altair as alt

def generate_random_chart(data):
    """
    Generates a random chart using Altair.
    """
    # Randomly select a chart type
    chart_type = random.choice(['bar', 'line', 'area', 'point', 'rule', 'interval', 'circle', 'square', 'triangle', 'star'])

    # Randomly select a color
    color = random.choice(alt.color_palette())

    # Generate the chart
    chart = alt.Chart(data).mark_[chart_type]().encode(
        alt.X('some_column:N', title='Some Column'),
        alt.Y('some_other_column:Q', title='Some Other Column'),
        alt.Color('some_other_column:Q', scale=alt.Scale(scheme=color))
    )

    return chart

# Example usage
data = alt.data.sample(100)
chart = generate_random_chart(data)
chart.display()