slider = pn.widgets.IntSlider(start=0, end=10)
img = pn.pane.JPG(f"https://picsum.photos/800/300?image=0", embed=False, height=300)
slider.jscallback(args={'img': img}, value="""
img.text = '<img src="https://picsum.photos/800/300?image='+cb_obj.value+'" width=800 height=300></img>'
""")
app = pn.Column(slider, img)
ace = pn.widgets.Ace(readonly=True, width=800, height=200, language='python', theme='monokai', value=\
"""slider = pn.widgets.IntSlider(start=0, end=10)
def slideshow(index):
url = f"https://picsum.photos/800/300?image={index}"
return pn.pane.JPG(url)
output = pn.bind(slideshow, slider)
app = pn.Column(slider, output)""")
app1 = pn.Tabs(('Output', app), ('Code', ace))
penguins = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv').dropna()
cols = list(penguins.columns)[2:6]
x = pn.widgets.Select(name='x', options=cols)
y = pn.widgets.Select(name='y', options=cols, value='bill_depth_mm')
n_clusters = pn.widgets.IntSlider(name='n_clusters', start=2, end=5, value=3)
def cluster(data, n_clusters):
kmeans = KMeans(n_clusters=n_clusters)
est = kmeans.fit(data)
return est.labels_.astype('str')
def plot(x, y, n_clusters):
penguins['labels'] = cluster(penguins.iloc[:, 2:6].values, n_clusters)
centers = penguins.groupby('labels').mean()
return (penguins.sort_values('labels').hvplot.scatter(
x, y, c='labels', hover_cols=['species'], line_width=1, size=60, frame_width=400, frame_height=400
).opts(marker=hv.dim('species').categorize({'Adelie': 'square', 'Chinstrap': 'circle', 'Gentoo': 'triangle'})) * centers.hvplot.scatter(
x, y, marker='x', color='black', size=400, padding=0.1, line_width=5
))
explanation = pn.pane.Markdown("""
This app applies k-means clustering on the Palmer Penguins dataset using scikit-learn, parameterizing the number of clusters and the variables to plot.
<br><br>
Each cluster is denoted by one color while the penguin species is indicated using markers:
<br><br>
● - Adelie, ▲ - Gentoo, ■ - Chinstrap
<br><br>
By comparing the two we can assess the performance of the clustering algorithm.
<br><br>
""")
code = pn.widgets.Ace(language='python', theme='monokai', height=360, value=\
"""x = pn.widgets.Select(name='x', options=cols)
y = pn.widgets.Select(name='y', options=cols, value='bill_depth_mm')
n_clusters = pn.widgets.IntSlider(name='n_clusters', start=2, end=5, value=3)
explanation = pn.pane.Markdown(...)
def plot_clusters(x, y, n_clusters):
...
pn.Row(
pn.WidgetBox(x, y, n_clusters, explanation),
pn.bind(plot, x, y, n_clusters)
)""", width=800)
app2 = pn.Tabs(
('Output', pn.Column(
pn.Row(
pn.WidgetBox(x, y, n_clusters, explanation),
pn.bind(plot, x, y, n_clusters)
)
)),
('Code', code)
)
pn.Row(pn.layout.HSpacer(), pn.Tabs(
('Penguin K-Means Clustering', app2),
('Slideshow', app1)
), pn.layout.HSpacer(), sizing_mode='stretch_width').embed(max_opts=4, json=True, json_prefix='json')