Interactive pie chart in bokeh; reactively swap in variables to plot

I am fairly new to Python and Bokeh so I am still trying to grasp how to interactively swap in variables to plot. At the moment I am trying to create a pie chart with bokeh widgets.

Here is what the pie chart looks like :-

from operator import index
from bokeh.models.widgets.markups import Div
import numpy as np
from numpy.lib import source
import pandas as pd
from bokeh.io import curdoc,show
from bokeh.layouts import column, row, gridplot
from bokeh.models import ColumnDataSource, Select, Slider, BoxSelectTool, LassoSelectTool, Tabs, Panel, LinearColorMapper, ColorBar, BasicTicker, PrintfTickFormatter, MultiSelect, DataTable, TableColumn
from bokeh.plotting import figure, curdoc
from bokeh.palettes import viridis, gray, cividis, Category20, Category20c
from bokeh.transform import factor_cmap,cumsum
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import classification_report, confusion_matrix, mean_squared_error, r2_score, recall_score, f1_score
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.cluster import KMeans
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from math import pi
from bokeh.transform import cumsum

np.random.seed(42)


print("step 1")
#define the categorical variable
category_a = ['A','B','C']
category_b = ['X','Y','Z']
print("step 2")
df_random = pd.DataFrame({
   'id': np.arange(0, 100),
   'date': pd.date_range(start='1/1/2021', periods=100, freq='D'),
   'month':np.random.randint(1, 12, 100),
   'sensor_1': np.random.uniform(0, 1,100),
   'sensor_2': np.random.uniform(10, 150, 100),
   'sensor_3': np.random.randint(0, 90, 100),
   'sensor_4': np.random.randint(0, 450, 100),
   'sensor_5': np.random.randint(0, 352, 100),
   'categorya': np.random.choice(category_a, 100, p=[0.2, 0.4, 0.4]),
   'categoryb': np.random.choice(category_b, 100, p=[0.6, 0.2, 0.2]),
})

column_choices = {
    "Sensor 1": "sensor_1",
    "Sensor 2": "sensor_2",
    "Sensor 3": "sensor_3",
    "Sensor 4": "sensor_4",
    "Sensor 5": "sensor_5"
}

column_choices_list = list(column_choices.values())

groupeddf = df_random.groupby('categorya')[column_choices_list].mean()
print(groupeddf)

groupeddf['angle'] = groupeddf['sensor_1']/groupeddf['sensor_1'].sum() * 2*pi
groupeddf['color'] = Category20c[len(groupeddf)]
source_pie = ColumnDataSource(data=groupeddf)

p_pie = figure(plot_height=350, title="Pie Chart", toolbar_location=None, tools="")

p_pie.wedge(x=0, y=1, radius=0.4,
        start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
        line_color="white", fill_color='color', legend='categorya', source=source_pie)



show(p_pie)

enter image description here

However, I am trying to add in the widget to change which column in df_random which is where I am tripping up:-

...

selecty_pie_var = Select(title="Select variable:", options=list(column_choices_list))

def callback(attr,old,new):
    df_platform['angle'] = df_platform[selecty_pie_var.value]/df_platform[selecty_pie_var.value].sum() * 2*pi
    df_platform['color'] = Category20c[len(df_platform)]
    source_pie.data = df_platform
    return source_pie

selecty_pie_var.js_on_change('value', callback)

layoutwithwidgets = row(selecty_pie_var,p_pie)

show(layoutwithwidgets)

And I imagine that the above to any competent Python user, just looks like a mess. Would someone be able to help me link the widget and the pie chart together so that it updates whenever I change the column? For example, sensor_1 is being plotted now, but I would like to be able to change it to sensor_2,sensor_3, etc.

Any help is greatly appreciated :)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum