Random Plotly Chart Generator

  • Share this:

Code introduction


This code defines a function that uses the Plotly library to randomly generate different types of charts, including scatter plots, bar charts, pie charts, heatmaps, contour plots, and surface plots.


Technology Stack : ['Plotly', 'random', 'numpy']

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import plotly.graph_objects as go

def random_plotly_chart():
    chart_types = ['scatter', 'bar', 'pie', 'heatmap', 'contour', 'surface']
    chart_type = random.choice(chart_types)
    
    if chart_type == 'scatter':
        fig = go.Scatter(x=[random.uniform(0, 10) for _ in range(10)], y=[random.uniform(0, 10) for _ in range(10)])
        fig.update_layout(title='Random Scatter Plot')
    elif chart_type == 'bar':
        fig = go.Bar(x=[f'Category {i}' for i in range(5)], y=[random.randint(1, 100) for _ in range(5)])
        fig.update_layout(title='Random Bar Chart')
    elif chart_type == 'pie':
        fig = go.Pie(labels=[f'Category {i}' for i in range(5)], values=[random.randint(1, 100) for _ in range(5)])
        fig.update_layout(title='Random Pie Chart')
    elif chart_type == 'heatmap':
        z = [[random.uniform(0, 1) for _ in range(10)] for _ in range(10)]
        fig = go.Heatmap(z=z)
        fig.update_layout(title='Random Heatmap')
    elif chart_type == 'contour':
        z = [[random.uniform(0, 1) for _ in range(10)] for _ in range(10)]
        fig = go.Contour(z=z)
        fig.update_layout(title='Random Contour Plot')
    elif chart_type == 'surface':
        z = [[random.uniform(0, 1) for _ in range(10)] for _ in range(10)]
        fig = go.Surface(z=z)
        fig.update_layout(title='Random Surface Plot')
    
    fig.show()