Randomly Generated Plotly Charts

  • Share this:

Code introduction


This function randomly generates a scatter plot, bar chart, or pie chart based on the input data.


Technology Stack : Plotly, Python library for creating interactive and publishable graphs

Code Type : The type of code

Code Difficulty :


                
                    
import random
import plotly.graph_objects as go

def random_plotly_chart(data):
    """
    Generate a random Plotly chart based on the type of data provided.
    """
    # Randomly select a chart type
    chart_type = random.choice(['scatter', 'bar', 'pie'])

    # Create a figure object
    fig = go.Figure()

    # Generate data based on the chosen chart type
    if chart_type == 'scatter':
        x = [random.randint(1, 100) for _ in range(len(data))]
        y = [random.randint(1, 100) for _ in range(len(data))]
        fig.add_trace(go.Scatter(x=x, y=y, mode='markers'))
    elif chart_type == 'bar':
        categories = [f'Category {i}' for i in range(len(data))]
        values = [random.randint(1, 100) for _ in range(len(data))]
        fig.add_trace(go.Bar(x=categories, y=values))
    elif chart_type == 'pie':
        categories = [f'Category {i}' for i in range(len(data))]
        values = [random.randint(1, 100) for _ in range(len(data))]
        fig.add_trace(go.Pie(labels=categories, values=values))

    # Show the figure
    fig.show()

# Example usage
data_size = 5
data = list(range(data_size))
random_plotly_chart(data)