Let’s first create a static scatter plot and then we will add interactive features to it.
alt.Chart(df).mark_circle(size=50).encode(
x='Price',
y='Distance',
color='Type'
).properties(
height=350, width=500
)
Before starting on the interactive plots, it is better to briefly mention the basic structure of Altait syntax. We start by passing the data to a top-level Chart object. The data can be in the form of a Pandas dataframe or a URL string pointing to a json or csv file.
Then we describe the type of visualization (e.g. mark_circle, mark_line, and so on). The encode function specifies what to plot in the given dataframe. Thus, anything we write in the encode function must be linked to the dataframe. Finally, we specify certain properties of the plot using the properties function.
Some part of the plot seems too overlapped in terms of the dots. It would look better if we can also view data points that belong to a specific type.
We can achieve this in two steps. The first step is to add a selection with the type column and bind it to the legend.
selection = alt.selection_multi(fields=['Type'], bind='legend')
It is not enough just to add a selection. We should somehow update the plot based on the selection. For instance, we can adjust the opacity of the data points according to the selected category by using the condition property with the opacity parameter.
alt.Chart(df).mark_circle(size=50).encode(
x='Price',
y='Distance',
color='Type',
opacity=alt.condition(selection, alt.value(1), alt.value(0.1))
).properties(
height=350, width=500
).add_selection(
selection
)