Fun with dynamic pyplot plotting code!

This app demonstrates the flexibilty Streamlit offers by making your plot code dynamic and controlled via widgets!

In the plot code below, the variables x_lim and y_lim are set and adjusted via two number_input Streamlit widgets.

Plotting code:

fig, ax = plt.subplots()
        
        genre_list = column_multiselect
        if genre_list:
          data = data.query("Genre in @genre_list").reset_index()
        
        lib.scatterplot(
          data=data, x='NA_Sales', y='Global_Sales', hue='Genre', 
          style='Genre', palette='bright', s=100
        )
        
        x_lim = min(x_lim, data.index.max())
        y_lim = min(y_lim, data.index.max())
        
        plt.title('NA Sales vs. Global Sales by Genre')
        plt.xlabel('NA Sales')
        plt.ylabel('Global Sales')
        plt.legend(title='Genre', bbox_to_anchor=(1.05, 1), loc='upper left')
        plt.grid(True)
        
        X_zoom = (data['NA_Sales'].sort_values(ascending=False)
                  .reset_index()['NA_Sales']
                  .loc[
                      data['NA_Sales']
                      .idxmax() + x_lim - 1
                   ]
                  )
        
        y_zoom = (data['Global_Sales'].sort_values(ascending=False)
                  .reset_index()['Global_Sales']
                  .loc[
                      data['NA_Sales']
                      .idxmax() + y_lim - 1
                   ]
                  )

        # Adjust the idxmax values to focus on a specific range
        plt.xlim(0, X_zoom + 1)
        plt.ylim(0, y_zoom + 1)
4 Likes

Great app! Thanks for sharing the Streamlit magic :slight_smile:

1 Like

This is fantastic @Andre-Codes :slight_smile:

Great work!

3 Likes