Random Chart Generation with Altair and Pandas

  • Share this:

Code introduction


This function generates random charts using the Altair library. It includes various types of charts such as bar charts, line charts, scatter plots, and text charts. The function accepts a Pandas DataFrame as input, randomly selects a chart type, and returns a JSON-formatted chart.


Technology Stack : The packages and technologies used in this code include Altair, Pandas, and JSON.

Code Type : The type of code

Code Difficulty :


                
                    
import altair as alt
import random
import pandas as pd

def random_chart(data):
    """
    Generate a random chart using Altair.
    """
    # Define a list of possible charts
    chart_types = [
        alt.Chart(data).mark_bar().encode(
            alt.X('some_categorical_field:O', title='Category'),
            alt.Y('some_numeric_field:Q', title='Value')
        ),
        alt.Chart(data).mark_line().encode(
            alt.X('some_datetime_field:T', title='Date'),
            alt.Y('some_numeric_field:Q', title='Value')
        ),
        alt.Chart(data).mark_point().encode(
            alt.X('some_numeric_field:Q', title='X Value'),
            alt.Y('some_numeric_field:Q', title='Y Value')
        ),
        alt.Chart(data).mark_text(align='left', baseline='middle').encode(
            alt.X('some_numeric_field:Q', title='Position'),
            alt.Y('some_numeric_field:Q', title='Position'),
            alt.Text('some_text_field:T', title='Text')
        )
    ]
    
    # Randomly select a chart type
    selected_chart = random.choice(chart_types)
    
    # Render the chart
    return selected_chart.to_json()

# Example usage
data = pd.DataFrame({
    'category': ['A', 'B', 'C', 'D'],
    'value': [10, 20, 30, 40]
})

chart_json = random_chart(data)
print(chart_json)