-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathinteractive_charts.qmd
More file actions
216 lines (159 loc) · 8.19 KB
/
interactive_charts.qmd
File metadata and controls
216 lines (159 loc) · 8.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
---
title: "Interactive Charts"
filters:
- whitphx/stlite
---
## An overview of supported interactive chart types in Streamlit
Streamlit provides support for several interactive chart libraries, including
- Plotly
- Bokeh
- Altair
- Vega-lite
It also provides its own simplified interactive chart types like `st.bar_chart`, which are simplified functions for plotting that use Altair behind the scenes.
:::{.callout-tip}
While all of these are valid options to use in your own dashboards, we will be focussing on plotly - specifically the 'plotly express' module, which makes it very quick and easy to create relatively complex interactive charts.
Arguably plotly express is simpler to use than the built-in streamlit plot types! It's also generally more customisable.
:::
:::{.callout-tip}
Each of the plot types mentioned above require a different streamlit command to display them.
- Plotly - `st.plotly_chart()`
- Bokeh - `st.bokeh_chart()`
- Altair - `st.altair_chart()`
- Vega-lite - `st.vega_lite_chart()`
The details and specific arguments that are available for each can be found in the Streamlit documentation [here](https://docs.streamlit.io/develop/api-reference/charts).
:::
## An example plotly chart in Streamlit
```{python}
#| eval: False
import streamlit as st
from palmerpenguins import load_penguins # <1>
import plotly.express as px # <2>
penguins = load_penguins() # <3>
fig = px.scatter( # <4>
penguins, # <5>
x='bill_length_mm', # <6>
y='bill_depth_mm',
color="sex", # <7>
title=f"Penguins Dataset - Bill Length (mm) vs Bill Depth (mm), coloured by Sex" # <8>
)
st.plotly_chart(fig) # <9>
```
1. Here we load in a package that will provide access to a dataset of penguin measurements.
2. We also need to load in the plotly.express module. The standard alias for this library is `px`.
3. We use the `load_penguins()` function to pull in the pandas dataframe of penguin measurements, assigning it to the variable `penguin`.
4. Plotly express (px) provides access to a wide range of simple plot types. Here, `px.scatter` sets up the chart as a scatterplot which expects, as a minimum, two columns of numeric values to assign the x and y position of a series of points on an axis. We save the output of this function to a variable, as we'll need to pass that variable to the relevant streamlit function later. A common variable name to use for this is `fig`.
5. We pass in the dataframe we want to plot as the first argument.
6. We specify the names of the columns we want to plot the values of on the x (horizontal) and y (vertical) axes. These can be surrounded by single ' or double " quotes. Note that we don't need to respecify the dataframe name here - purely the column name as a string.
8. Optionally we can pass in a column containing a categorical variable (which can just be a column of strings) to use to colour the points. Here, we have a column called 'sex' which just contains the values 'Male' or 'Female'; passing this in will mean our male penguin points will have one colour, and female another.
9. Finally, we pass the variable corresponding to our plotly plot object to the `st.plotly_plot()` function.
```{stlite-python}
import micropip
await micropip.install("setuptools")
await micropip.install("palmerpenguins")
await micropip.install("plotly")
import streamlit as st
from palmerpenguins import load_penguins
from plotly import express as px
penguins = load_penguins()
fig = px.scatter(penguins, x='bill_length_mm', y='bill_depth_mm', color="sex",
title=f"Penguins Dataset - Bill Length (mm) vs Bill Depth (mm), coloured by Sex")
st.plotly_chart(fig)
```
## Making use of the available space
Many streamlit components have a parameter called `use_container_width`.
We showed the impact of this parameter on static charts in the previous chapter.
When set to `True` in something like `st.plotly_chart`, it ensures the output is rescaled to use the maximum available width of the screen.
The parameter is set to `True` by default in newer versions of Streamlit - but you may wish to use 'False' in certain cases.
:::{.callout-tip}
This can become particularly valuable when we start to explore layout options like columns later in the book.
:::
:::{.callout-note}
Depending on the width of the app window itself, the impact of this function is sometimes not very obvious; it may become more apparent in your own app compared to the example below.
:::
```{python}
#| eval: False
import streamlit as st
from palmerpenguins import load_penguins
import plotly.express as px
penguins = load_penguins()
fig = px.scatter(
penguins,
x='bill_length_mm',
y='bill_depth_mm',
color="sex",
title=f"Penguins Dataset - Bill Length (mm) vs Bill Depth (mm), coloured by Sex",
width=300,
height=400
)
st.subheader("use_container_width=False")
st.plotly_chart(fig, use_container_width = False, key="plot_1")
st.subheader("use_container_width=True")
st.plotly_chart(fig, use_container_width = True, key="plot_2")
```
```{stlite-python}
import micropip
await micropip.install("setuptools")
await micropip.install("palmerpenguins")
await micropip.install("plotly")
import streamlit as st
from palmerpenguins import load_penguins
from plotly import express as px
penguins = load_penguins()
fig = px.scatter(penguins, x='bill_length_mm', y='bill_depth_mm', color="sex",
title=f"Penguins Dataset - Bill Length (mm) vs Bill Depth (mm), coloured by Sex",
width=300,
height=400)
st.subheader("use_container_width=False")
st.plotly_chart(fig, use_container_width = False, key="plot_1")
st.subheader("use_container_width=True")
st.plotly_chart(fig, use_container_width = True, key="plot_2")
```
## Sneak Peak: Reacting to user inputs
While we haven't gone into detail about user inputs yet, here is an example of a plotly chart updating based on the options a user is selecting.
```{python}
#| eval: False
import streamlit as st
from palmerpenguins import load_penguins
from plotly import express as px
penguins = load_penguins()
axis_options = [
'bill_length_mm', 'bill_depth_mm' 'flipper_length_mm'
] # <1>
col_1 = st.selectbox(
"Select the column to use for the x axis", axis_options
) # <2>
fig = px.scatter(
penguins,
x=col_1, # <3>
y='body_mass_g',
color='species',
title=f"Penguins Dataset - {col_1} vs Body Mass (g), coloured by Species" # <4>
)
st.plotly_chart(fig)
```
1. In this example, we want users to be able to choose one of three columns to use for the x axis values, with the y axis values and column used for colour being pre-set. We start by creating a list of the column names; these must exact match the way the column name is written in the dataframe, including case, spaces and any underscores.
2. Next, we use one of streamlit's built-in user input gathering functions. A selectbox gives the user a drop-down list of predefined options to select from. We pass this a label (to indicate to the user what they are selecting) and the list of possible column names. We store the output of this in a variable, which we've called `col_1` here. The contents of `col_1` will be whichever of the three provided column names the user has selected. By default, the first column name in the list will be selected when the app loads.
3. Here, we pass in `col_1` when creating our plotly plot. When the app executes, the variable `col_1` will be replaced with the name of the column the user has selected, which will then be used by plotly when constructing the plot.
4. We can also use this input to make the title of the plot update in response to the selected variable.
```{stlite-python}
import micropip
await micropip.install("setuptools")
await micropip.install("palmerpenguins")
await micropip.install("plotly")
import streamlit as st
from palmerpenguins import load_penguins
from plotly import express as px
penguins = load_penguins()
axis_options = ['bill_length_mm', 'bill_depth_mm',
'flipper_length_mm']
col_1 = st.selectbox(
"Select the column to use for the x axis", axis_options
)
fig = px.scatter(
penguins,
x=col_1,
y='body_mass_g',
color='species',
title=f"Penguins Dataset - {col_1} vs Body Mass (g), coloured by Species")
st.plotly_chart(fig)
```