Random Chart Generation with Altair

  • Share this:

Code introduction


This function uses the Altair library to generate a data visualization chart based on randomly selected chart types and encoding channels.


Technology Stack : Altair, Pandas

Code Type : Custom Function

Code Difficulty : Intermediate


                
                    
import random
import altair as alt
import pandas as pd

def generate_random_chart(data):
    """
    Generates a random chart using Altair based on the input data.
    """
    # Randomly select a mark type
    mark_type = random.choice(['circle', 'square', 'triangle', 'cross', 'x', 'diamond', 'hbar', 'vhbar', 'line', 'rule', 'bar'])
    
    # Randomly select an encoding channel
    encoding_channel = random.choice(['x', 'y', 'color', 'size', 'shape', 'opacity'])
    
    # Create a simple chart
    chart = alt.Chart(data) \
        .mark(mark_type) \
        .encode(
            alt_encoding_channel if encoding_channel in ['x', 'y'] else 'color',  # Randomly choose encoding channel
            alt_encoding_channel + "=Q(*)"  # Quantitative encoding channel
        )
    
    return chart

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

chart = generate_random_chart(data)
chart.show()                
              
Tags: