You can download this code by clicking the button below.
This code is now available for download.
This function creates a random bar chart using the Vega library. The function first randomly selects a color palette and a field as the basis for the bars. Then, it defines a Vega chart specification including the data source, marks, and encoding. Finally, it renders the chart using the Vega library.
Technology Stack : Python, Vega, Pandas
Code Type : The type of code
Code Difficulty :
import random
def random_bar_chart(data):
"""
Generates a random bar chart using Vega library.
"""
# Randomly select a color palette
palette = random.choice([
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
])
# Randomly select a field for the bars
field = random.choice(data.columns)
# Define the Vega bar chart specification
spec = {
"$schema": "https://vega.github.io/schema/vega/v5.json",
"height": 400,
"width": 600,
"data": [
{
"name": "table",
"values": data
}
],
"marks": [
{
"type": "bar",
"from": {"data": "table"},
"encode": {
"enter": {
"x": {"field": field, "type": "quantitative"},
"y": {"field": "count", "type": "quantitative"},
"fill": {"value": random.choice(palette)}
}
}
}
],
"encoding": {
"y": {
"field": "count",
"type": "quantitative",
"axis": {"title": "Count"}
}
}
}
# Render the Vega bar chart
import vega
vega.display(spec)