Random Altair Chart Generation with Mark Selection

  • Share this:

Code introduction


This code defines a function that generates a random chart type using the Altair library, and uses randomly selected marks. The function accepts data, width, and height as parameters.


Technology Stack : The code defines a function that generates a random chart type using the Altair library, and uses randomly selected marks. The function accepts data, width, and height as parameters.

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
from altair import Chart

def random_altair_chart(width, height, data):
    """
    Generates a random Altair chart based on the given data.
    """
    # Randomly select a chart type
    chart_type = random.choice(['bar', 'line', 'point', 'area', 'bar', 'histogram', 'text', 'rule'])

    # Randomly select a mark
    mark = random.choice(['circle', 'square', 'cross', 'diamond', 'triangle', 'x', 'hline', 'vline', 'rule'])

    # Create the chart
    chart = Chart(data=data, width=width, height=height).mark(mark).encode(
        x='x:O', y='y:Q', color='color:N'
    )

    if chart_type == 'bar':
        chart = chart.transform_filter('datum.x != null')

    return chart

# Example usage
data = {
    "x": ['A', 'B', 'C', 'D'],
    "y": [1, 3, 2, 5],
    "color": ['red', 'green', 'blue', 'yellow']
}

chart = random_altair_chart(400, 300, data)
chart.display()