You can download this code by clicking the button below.
This code is now available for download.
The function generates a random chart based on a provided DataFrame and chart type. The function first randomly selects fields from the DataFrame, then generates the corresponding Altair chart based on the chart type (bar, line, or scatter).
Technology Stack : Altair, Pandas
Code Type : Python Function
Code Difficulty : Intermediate
import random
import altair as alt
import pandas as pd
def generate_random_chart(dataframe, chart_type):
"""
Generates a random chart from a given dataframe and chart type.
Parameters:
- dataframe (pandas.DataFrame): The dataframe to use for generating the chart.
- chart_type (str): The type of chart to generate (e.g., 'bar', 'line', 'scatter').
Returns:
- alt.Chart: The generated chart.
"""
# Select random fields from the dataframe to use in the chart
field1 = random.choice(dataframe.columns)
field2 = random.choice(dataframe.columns)
if field1 == field2:
field2 = random.choice([col for col in dataframe.columns if col != field1])
# Generate the chart based on the chart type
if chart_type == 'bar':
chart = alt.Chart(dataframe).mark_bar().encode(
x=field1,
y='count()'
)
elif chart_type == 'line':
chart = alt.Chart(dataframe).mark_line().encode(
x=field1,
y=field2
)
elif chart_type == 'scatter':
chart = alt.Chart(dataframe).mark_point().encode(
x=field1,
y=field2
)
else:
raise ValueError("Unsupported chart type. Choose from 'bar', 'line', 'scatter'.")
return chart
# Example usage
data = pd.DataFrame({
'Category': ['A', 'B', 'C', 'D'],
'Value': [10, 20, 30, 40]
})
chart = generate_random_chart(data, 'bar')
chart.display()