Random Bar Chart Generation with Matplotlib

  • Share this:

Code introduction


This function creates a random bar chart using matplotlib, where the x-axis is labeled with the input data, and the y-axis contains randomly generated data.


Technology Stack : matplotlib, numpy

Code Type : Function

Code Difficulty : Intermediate


                
                    
def create_random_bar_chart(data):
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate random x-axis labels
    x = np.arange(len(data))
    # Generate random y-axis data
    y = np.random.rand(len(data))
    
    # Create a new figure and axis
    fig, ax = plt.subplots()
    
    # Create a bar chart
    ax.bar(x, y, color='skyblue')
    
    # Set the x-axis labels
    ax.set_xticks(x)
    ax.set_xticklabels(data)
    
    # Set the y-axis label
    ax.set_ylabel('Values')
    
    # Set the title of the chart
    ax.set_title('Random Bar Chart')
    
    # Display the plot
    plt.show()