Creating Bar Charts with Plotly in Python

  • Share this:

Code introduction


This function creates a bar chart using the Plotly library's GraphObjects module. It takes data, x-axis title, and y-axis title as parameters and displays a bar chart.


Technology Stack : Python, Plotly

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import plotly.graph_objects as go

def create_bar_chart(data, x_title, y_title):
    # Create a trace
    trace = go.Bar(x=data['x'], y=data['y'], name='Sample Data')

    # Create layout
    layout = go.Layout(
        title='Bar Chart Example',
        xaxis=dict(title=x_title),
        yaxis=dict(title=y_title)
    )

    # Plot the figure
    fig = go.Figure(data=[trace], layout=layout)
    fig.show()

# Example usage
data_example = {
    'x': ['A', 'B', 'C', 'D'],
    'y': [10, 11, 12, 13]
}

create_bar_chart(data_example, 'Category', 'Value')                
              
Tags: