You can download this code by clicking the button below.
This code is now available for download.
This function generates a random chart using the Altair library based on the provided DataFrame data. It randomly selects the chart type, color, mark, and fields used for the x-axis, y-axis, and legend.
Technology Stack : Altair, Pandas, NumPy
Code Type : Custom function
Code Difficulty : Intermediate
import altair as alt
import pandas as pd
import numpy as np
import random
def generate_random_chart(data):
"""
Generate a random chart using Altair based on the provided data.
Parameters:
data (pandas.DataFrame): The data to be used for the chart.
"""
# Randomly select a chart type
chart_type = random.choice(['bar', 'line', 'scatter', 'area', 'point', 'rule', 'interval', 'bar', 'text'])
# Randomly select a color for the chart
color = random.choice(['blue', 'green', 'red', 'purple', 'orange', 'yellow'])
# Randomly select a mark for the chart
mark = random.choice(['circle', 'square', 'triangle', 'cross', 'diamond', 'x', 'asterisk'])
# Generate the chart
chart = alt.Chart(data) \
.mark_$(mark=mark, color=color) \
.encode(
x=random.choice(data.columns), # Randomly choose the x-axis field
y=random.choice(data.columns), # Randomly choose the y-axis field
tooltip=[random.choice(data.columns)] # Randomly choose the tooltip field
)
return chart
# Example usage
data = pd.DataFrame({
'A': np.random.rand(100),
'B': np.random.rand(100),
'C': np.random.rand(100)
})
chart = generate_random_chart(data)
chart.display()