Skip to content

Commit 0f576cd

Browse files
committed
update
1 parent 12f4fa2 commit 0f576cd

4 files changed

Lines changed: 46 additions & 24 deletions

File tree

_episodes/05-seaborn-viz.md

Lines changed: 46 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ surveys_complete = pd.read_csv('surveys_complete.csv', index_col=0)
6363
Let's start with a basic scatterplot. We'll simply plot the weight on the horizontal axis and the hind foot length on the vertical axis. This uses the seaborn function `.lmplot()`. This function can take a Pandas DataFrame directly. It also will fit a regression line, by default. Since we may not want to visualize these data with a regression line, we will use the `fit_reg=False` argument.
6464

6565
~~~
66-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False)
66+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False)
6767
~~~
6868
{: .python}
6969

@@ -79,7 +79,7 @@ sns.set(font_scale=1.5)
7979
This will increase the font size of the labels by 50% in all of our subsequent plots.
8080

8181
~~~
82-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False)
82+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False)
8383
~~~
8484
{: .python}
8585

@@ -90,7 +90,7 @@ The plot size is small, by default, and with seaborn, there isn't a way to chang
9090
For `.lmplot()`, we can set the plot size directly as arguments in the function call using the `size` and `aspect` arguments. These arguments control the height and width of the object, respectively.
9191

9292
~~~
93-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5)
93+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5)
9494
~~~
9595
{: .python}
9696

@@ -101,7 +101,7 @@ sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, he
101101
One issue with this plot is that because we have a large dataset, it is difficult to adequately visualize the points on our graph. This is called "[overplotting](https://python-graph-gallery.com/134-how-to-avoid-overplotting-with-python/)". One way to avoid this is to change the size of the marker. Here we use the argument `scatter_kws` that takes a _dictionary_ of keywords and values that are passed to the matplotlib `scatter` function.
102102

103103
~~~
104-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, scatter_kws={"s": 5})
104+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, scatter_kws={"s": 5})
105105
~~~
106106
{: .python}
107107

@@ -110,7 +110,7 @@ sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, he
110110
Alternatively, we can change the marker type using the `markers` keyword argument. By default, `lmplot()` sets `markers='8'`. If we want to change the marker, we must use the correct [matplotlib code](https://matplotlib.org/examples/lines_bars_and_markers/marker_reference.html). Let's change the markers to X-es:
111111

112112
~~~
113-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, markers='x')
113+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, markers='x')
114114
~~~
115115
{: .python}
116116

@@ -119,7 +119,7 @@ sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, he
119119
Another way to avoid overplotting is to use transparency so that regions of the plot with many points are darker. This is achieved using the `scatter_kws` argument and setting the alpha value. (This is using [alpha compositing](https://en.wikipedia.org/wiki/Alpha_compositing).)
120120

121121
~~~
122-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, scatter_kws={'alpha':0.3})
122+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete, fit_reg=False, height=8, aspect=1.5, scatter_kws={'alpha':0.3})
123123
~~~
124124
{: .python}
125125

@@ -131,8 +131,9 @@ sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, he
131131
We can also specify that the `species_id` labels indicate categories that determine a point's color:
132132

133133
~~~
134-
sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8,
135-
aspect=1.5, scatter_kws={'alpha':0.3,"s": 50}, hue='species_id', markers='D')
134+
sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete,
135+
fit_reg=False, height=8, aspect=1.5, scatter_kws={'alpha':0.3,"s": 50},
136+
hue='species_id', markers='D')
136137
~~~
137138
{: .python}
138139

@@ -145,8 +146,10 @@ sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, he
145146
There are different ways to set figure properties using seaborn. For `.lmplot()`, we can create a figure variable and use a member method of tat variable to set the axis labels.
146147

147148
~~~
148-
my_fig = sns.lmplot("weight", "hindfoot_length", data=surveys_complete, fit_reg=False, height=8,
149-
aspect=1.5, scatter_kws={'alpha':0.3,"s": 50}, hue='species_id', markers='D')
149+
my_fig = sns.lmplot(x="weight", y="hindfoot_length", data=surveys_complete,
150+
fit_reg=False, height=8, aspect=1.5,
151+
scatter_kws={'alpha':0.3,"s": 50},
152+
hue='species_id', markers='D')
150153
my_fig.set_axis_labels('Weight (g)', 'Hindfoot Length (mm)')
151154
~~~
152155
{: .python}
@@ -165,8 +168,10 @@ my_fig.set_axis_labels('Weight (g)', 'Hindfoot Length (mm)')
165168
> > ## Solution
166169
> >
167170
> > ~~~
168-
> > my_fig = sns.lmplot("weight", "hindfoot_length", data=surveys_complete[surveys_complete.plot_id == 12],
169-
fit_reg=False, height=8, aspect=1.5, scatter_kws={'alpha':0.3,"s": 200},
171+
> > my_fig = sns.lmplot(x="weight", y="hindfoot_length",
172+
data=surveys_complete[surveys_complete.plot_id == 12],
173+
fit_reg=False, height=8, aspect=1.5,
174+
scatter_kws={'alpha':0.3,"s": 200},
170175
hue='sex', markers='8')
171176
my_fig.set_axis_labels('Weight (g)', 'Hindfoot Length (mm)')
172177
> > ~~~
@@ -196,7 +201,7 @@ Now, every time we create a new plot that returns a matplotlib Axes object, we c
196201
197202
~~~
198203
fig, ax = plt.subplots(figsize=plot_dims)
199-
sns.boxplot('species_id','hindfoot_length', data=surveys_complete)
204+
sns.boxplot(x='species_id', y='hindfoot_length', data=surveys_complete)
200205
ax.set(xlabel='Species ID', ylabel='Hindfoot Length (mm)')
201206
~~~
202207
{: .python}
@@ -210,8 +215,9 @@ An easy way to do this is to create a new graph variable from our `.violinplot()
210215
211216
~~~
212217
fig, ax = plt.subplots(figsize=plot_dims)
213-
g = sns.violinplot('weight','species_id', data=surveys_complete, linewidth=0.2, orient="h", cut=0)
214-
g.set_xscale('log', basex=10)
218+
g = sns.violinplot(x='weight', y='species_id', data=surveys_complete,
219+
linewidth=0.2, orient="h", cut=0)
220+
g.set_xscale('log', base=10)
215221
ax.set(ylabel='Species ID', xlabel='Weight (g)')
216222
~~~
217223
{: .python}
@@ -228,7 +234,7 @@ ax.set(ylabel='Species ID', xlabel='Weight (g)')
228234
> >
229235
> > ~~~
230236
> > fig, ax = plt.subplots(figsize=plot_dims)
231-
sns.violinplot(x = 'sex', y = 'weight', data=surveys_complete[surveys_complete.species_id == 'OL'])
237+
sns.violinplot(x='sex', y='weight', data=surveys_complete[surveys_complete.species_id == 'OL'])
232238
> > ~~~
233239
> > {: .python}
234240
> >
@@ -238,21 +244,21 @@ sns.violinplot(x = 'sex', y = 'weight', data=surveys_complete[surveys_complete.s
238244
239245
# Histograms
240246
241-
Often, a histogram is a better way to visualize a distribution. This is relatively simple using seaborn's `.distplot()` function. This function does not take a Pandas DataFrame, but can take a Pandas Series (i.e., column in our DataFrame). This function also can take come other arguments like `color`, which takes values that specify the color of histogram based on [matplotlib's colors](https://matplotlib.org/api/colors_api.html). We will make our plot cyan using the `'c'` color code.
247+
Often, a histogram is a better way to visualize a distribution. This is relatively simple using seaborn's `.displot()` function. This function does not take a Pandas DataFrame, but can take a Pandas Series (i.e., column in our DataFrame). This function also can take come other arguments like `color`, which takes values that specify the color of histogram based on [matplotlib's colors](https://matplotlib.org/api/colors_api.html). We will make our plot cyan using the `'c'` color code. Additionally, we will specify `bins=50` so that our histogram is not plotted using too many or too few bins.
242248
243249
~~~
244-
fig, ax = plt.subplots(figsize=plot_dims)
245-
sns.distplot(surveys_complete['weight'], color='c')
250+
sns.displot(surveys_complete['weight'], color='c',bins=50,
251+
height=8, aspect=1.5)
246252
~~~
247253
{: .python}
248254
249255
![png](../fig/05-seaborn-distplot-1.png)
250256
251-
By default, the `.distplot()` function plots the histogram as a density plot with the kernel density estimate overlaid as a darker line on the graph. This may not be necessary and we may instead want the vertical axis to represent the counts in each bin. We can further adjust the appearance of the histogram to make the bars more apparent and increase the number of bins.
257+
By default, the `.displot()` function plots the density as a histogram, alternatively, you can plot a kernel density estimate by setting the `kind` argument to `kind="kde"` (the default is `kind="hist"`) and removing the `bins` argument.
252258
253259
~~~
254-
fig, ax = plt.subplots(figsize=plot_dims)
255-
sns.distplot(surveys_complete['weight'], kde=False, color='c', hist_kws=dict(edgecolor="k", linewidth=1), bins=100)
260+
sns.displot(surveys_complete['weight'], color='k', kind="kde",
261+
height=8, aspect=1.5)
256262
~~~
257263
{: .python}
258264
@@ -322,7 +328,23 @@ out.close()
322328
~~~
323329
{: .python}
324330
325-
## Comparing densities in bokeh using ridgeline plots
331+
If you open the file you created in your web browser, you now have an interactive version of your figure. You can then use this to embed in a website.
332+
333+
> ## Take-Home Challenge: More Visualizations in Python
334+
>
335+
> Continue to use `seaborn` and `bokeh` to try out different visualizations.
336+
>
337+
> 1. Produce a histogram of the hindfoot length for only the species observed in the genus _Peromyscus_. Note that this particular dataset includes a column called `"genus"`. So you can subset out only the entries for _Peromyscus_ individuals. Try making the histogram using both `seaborn` and `bokeh`. Consider altering the bin numbers to help visualize the distribution.
338+
>
339+
> 2. This dataset also has a column called `"plot_type"`. That says what kind of plot in which the animal was captured. The different plot types are specific experimental set-ups for this kind of study. Create a visualization that helps us better understand how the species (`"species_id"`) might be influenced by the plot type. For example, are some species prevented from entering certain plot types?
340+
>
341+
> > ## Solutions
342+
> >
343+
> > The solutions will be posted in 4 days. Feel free to use the `#scripting_help` channel in Slack to discuss these exercises.
344+
> {: .solution}
345+
{: .challenge}
346+
347+
<!-- ## Comparing densities in bokeh using ridgeline plots
326348
327349
A cool way of visualizing multiple histograms is to use what is called a "ridgeline" plot. There is a nice package in R called [`ggridges`](https://github.com/clauswilke/ggridges) that allows you to create these plot. Here is the additional code needed to make this plot using bokeh in Python. (To get this to work, you must first install the package `colorcet` using: `conda install colorcet`.)
328350
@@ -355,7 +377,7 @@ show(ridgeline)
355377
{: .python}
356378
357379
{% include weight_ridgeline_bokeh.html %}
358-
380+
-->
359381
360382
361383
<!--

fig/05-seaborn-distplot-1.png

-13.9 KB
Loading

fig/05-seaborn-distplot-2.png

14.4 KB
Loading

fig/bokeh1.png

27 Bytes
Loading

0 commit comments

Comments
 (0)