You can download this code by clicking the button below.
This code is now available for download.
This custom function generates random Altair charts based on the input DataFrame, including bar charts, line charts, area charts, scatter plots, and more. The function first randomly selects a chart type and then selects a mark type, and uses the Altair library to create the chart.
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(dataframe):
# Randomly select a chart type
chart_types = ["bar", "line", "area", "scatter", "circle", "square", "triangle", "diamond"]
chart_type = random.choice(chart_types)
# Randomly select a mark type for the chart
mark_types = ["circle", "square", "triangle", "cross", "x", "diamond", "plus", "minus", "none"]
mark_type = random.choice(mark_types)
# Create the chart based on the randomly selected type and mark
chart = alt.Chart(dataframe).mark_$(mark_type).encode(
alt.X('column:O', title='X Axis'),
alt.Y('value:Q', title='Y Axis')
).type(chart_type)
return chart
# Example usage
data = pd.DataFrame({
'column': ['A', 'B', 'C', 'D'],
'value': [10, 20, 15, 5]
})
chart = generate_random_chart(data)
chart.display()