Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
2 years ago
Solved

Field Parameter pass to Python visual

Hey Guys!   I want to create a BoxPlot with a python chart. But I want to switch the x-axis between a week (Mon, Tue, ...) and month (jan, feb, ...). I think it should be possible to use a field pa...
  • Anonymous's avatar
    Anonymous
    2 years ago

    Hey guys!

     

    I found out. Here is the final code:

     

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt

    # Define the desired order for months and weekdays
    months_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    days_order = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

    # Determine the period column (Month or Day) and the doubleValue column
    period_column = dataset.columns[1]  # Assumption: period column is the second column
    value_column = dataset.columns[0]   # Assumption: doubleValue column is the first column

    # Convert the period column to a categorical type with the correct order
    if period_column == 'Month':
        dataset[period_column] = pd.Categorical(dataset[period_column], categories=months_order, ordered=True)
    elif period_column == 'Day':
        dataset[period_column] = pd.Categorical(dataset[period_column], categories=days_order, ordered=True)

    # Create the BoxPlot using matplotlib
    # Create the list of data arrays for the boxplot
    data = [dataset[dataset[period_column] == period][value_column].values for period in dataset[period_column].cat.categories]

    # Create the boxplot
    plt.boxplot(data, labels=dataset[period_column].cat.categories)

    # Add labels
    plt.xlabel(period_column)

    # Show the plot
    plt.show()

     

    The first part deals with the order of months/days (otherwise it would be alphabetical)

     

     

    Hope this can help somebody