Generating Bar Charts with Altair

  • Share this:

Code introduction


This function generates a bar chart using the Altair library. It accepts a DataFrame, the names of the data columns for the X-axis and Y-axis, and an optional title.


Technology Stack : Altair, Pandas

Code Type : Function

Code Difficulty : Intermediate


                
                    
import altair as alt
import pandas as pd
import numpy as np

def generate_bar_chart(dataframe, x_column, y_column, title):
    """
    This function generates a bar chart using Altair library.
    """
    # Create a bar chart
    bar_chart = alt.Chart(dataframe).mark_bar().encode(
        x=x_column,
        y=alt.Y(y_column, title=title)
    ).properties(
        title=title
    )

    return bar_chart

# Example usage:
# dataframe = pd.DataFrame({
#     'Category': ['A', 'B', 'C', 'D'],
#     'Value': [10, 20, 30, 40]
# })
# bar_chart = generate_bar_chart(dataframe, 'Category', 'Value', 'Values by Category')
# bar_chart.display()                
              
Tags: