Random Bar Chart Generation with Plotly

  • Share this:

Code introduction


This code defines a function named random_bar_chart that accepts a dictionary as input, with the keys and values of the dictionary serving as the x-axis and y-axis data for the chart. The function uses the GraphObjects module from Plotly to create a bar chart and randomly generates data. Then, it updates the chart's layout and displays the chart.


Technology Stack : Plotly, Python, GraphObjects, bar chart, random data generation

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import plotly.graph_objects as go
import random

def random_bar_chart(data):
    # Generate a random bar chart
    fig = go.Figure(data=[go.Bar(x=data.keys(), y=data.values())])
    
    # Update the layout
    fig.update_layout(title='Random Bar Chart', xaxis_title='Categories', yaxis_title='Values')
    
    # Show the figure
    fig.show()

# Example usage:
data = {
    'Category A': random.randint(1, 100),
    'Category B': random.randint(1, 100),
    'Category C': random.randint(1, 100),
    'Category D': random.randint(1, 100),
    'Category E': random.randint(1, 100)
}

random_bar_chart(data)