Using mplcursor for hover functionality in Bar Graph using Python

29 views Asked by At

I am trying to make a desktop application using pyqt, on e of the features which I want to add is reading multiple csv files and plotting the graph accordingly. When I am hoovering over one bar I should get the sub details like simple, medium and complex details along with a total. But when I am trying my code I am successfull in getting the total count but I also want to display simple, medium complex details which is coming but the values are incorrect.

This is my function:

def hover_formatter(event):
    # This part is only needed if you want to handle hover events separately
    total_count = event.artist[0].get_height()
    month_index, category_index = map(int, event.target)

    # Access the x and y coordinates directly
    month_index, category_index = map(int, event.target)

    # Check if the indices are within bounds
    if (
        0 <= month_index < len(pivot_df.index)
        and 0 <= category_index < len(pivot_df.columns)
    ):
        # Try to get the category directly
        try:
            category = pivot_df.columns[category_index]
        except Exception as e:
            # If it fails, use the previous approach
            category = pivot_df.columns.get_level_values(1)[category_index]

        # Get the corresponding month name
        month = pivot_df.index[month_index]

        # Access values for the selected category and month
        simple_value = combined_df[
            (combined_df['Month'] == month) & (combined_df['Category'] == category)
        ]['Simple'].sum()
        medium_value = combined_df[
            (combined_df['Month'] == month) & (combined_df['Category'] == category)
        ]['Medium'].sum()
        complex_value = combined_df[
            (combined_df['Month'] == month) & (combined_df['Category'] == category)
        ]['Complex'].sum()

        text = (
            f"Category: {category}\nMonth: {month}\n"
            f"Total: {total_count}\nSimple: {simple_value}\nMedium: {medium_value}\nComplex: {complex_value}"
        )
        event.annotation.set_text(text)
    else:
        event.annotation.set_text("Invalid index")

    # Add data labels to the bars
    ax.bar_label(event.artist, fmt='%d', label_type='edge', fontsize=8, color='black', weight='bold')

cursor.connect("add", hover_formatter)

The output it gives is:

Output Image -- >

If you observe carefully I get the same info for same heights.

**This is the format of my csv file and all csv files will have the same format. **

Category,Simple,Medium,Complex
QA,23,0,0
Package,1,0,0
Incident,1,2,1
PRF Creations,0,0,0
0

There are 0 answers