Random Chart Generation with Altair

  • Share this:

Code introduction


This function randomly selects a chart type from the Altair library, then randomly selects a data field, color scale, and mark type to generate a random chart.


Technology Stack : Altair library, Python programming language

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import altair as alt

def random_chart(data):
    # Randomly select a chart type from Altair's chart types
    chart_type = random.choice([alt.Chart, alt.Violin, alt.Bar, alt.Line, alt.Point, alt.Pie])
    
    # Generate a random chart based on the selected type
    chart = chart_type(data=data)
    
    # Randomly select an encoding field
    encoding_field = random.choice(data.columns)
    
    # Randomly select a color scale
    color_scale = alt.ColorScale(colors=["blue", "green", "red"])
    
    # Randomly select a mark type
    mark_type = random.choice([alt.MarkPoint, alt.MarkLine, alt.MarkCircle, alt.MarkSquare, alt.MarkTriangle])
    
    # Construct the chart with random properties
    chart = chart mark=mark_type(size=50) \
                 encoding=alt.Encoding().color(encoding_field, scale=color_scale)
    
    return chart

# Example usage
data = alt.data.NumericalTimeSeries()
chart = random_chart(data)
print(chart.to_json())