You can download this code by clicking the button below.
This code is now available for download.
This function generates a random chart from the provided DataFrame data using Altair, including randomly selecting the mark type, color, and axis fields.
Technology Stack : Altair, Pandas
Code Type : Custom function
Code Difficulty : Intermediate
import altair as alt
import pandas as pd
import random
def generate_random_chart(data):
"""
Generates a random chart from the provided data using Altair.
"""
# Randomly choose a mark type
mark_type = random.choice(['bar', 'line', 'point', 'area', 'rule', 'circle', 'square', 'cross', 'triangle', 'asterisk'])
# Randomly choose a color
color = random.choice(alt.color_scale_discrete(name='color', domain=['low', 'high']))
# Randomly choose a field for the x-axis
x_field = random.choice(list(data.columns))
# Randomly choose a field for the y-axis
y_field = random.choice(list(data.columns))
# Create the chart
chart = alt.Chart(data) \
.mark(mark_type, color=color) \
.encode(
alt.X(x_field, title=x_field),
alt.Y(y_field, title=y_field)
)
return chart
# Example usage:
# data = pd.DataFrame({
# 'Category': ['A', 'B', 'C', 'D'],
# 'Value': [10, 20, 15, 5]
# })
# chart = generate_random_chart(data)
# chart.display()