seaborn_2_chapter1.pdf

chapter 1

1.1 Python Visualization Landscape

  • Matplotlib
  • Pandas
  • Seaborn ```python

    1. Matplotlib

    import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv(“wines.csv”) fig, ax = plt.subplots() ax.hist(df[‘alcohol’])

2. Pandas

import pandas as pd df = pd.read_csv(“wines.csv”) df[‘alcohol’].plot.hist()

3. Seaborn

import seaborn as sns sns.distplot(df[‘alcohol’])

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/26718834/1649132582564-d5857e38-4867-4d58-9bce-0b23b9c9d25c.png#clientId=u3029df3e-cc07-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=285&id=u5dbbbafa&margin=%5Bobject%20Object%5D&name=image.png&originHeight=560&originWidth=885&originalType=binary&ratio=1&rotation=0&showTitle=false&size=74575&status=done&style=none&taskId=ub60138d5-9b19-48fa-a5fb-fcba531a459&title=&width=451)
  2. <a name="gfH4Z"></a>
  3. ## 1.2 Using the distribution plot
  4. ```python
  5. # A kde curve and rug plot can be combined
  6. sns.distplot(df['alcohol'], kde=False, bins=10)
  7. sns.distplot(df['alcohol'], hist=False, rug=True)
  8. sns.distplot(df['alcohol'], hist=False, rug=True, kde_kws={'shade':True})

1.3 Regression Plots: a scatter plot with a regression line

sns.regplot(x="alcohol", y="pH", data=df)

image.png

  • regplot() : axes-level function
  • lmplot() : figure-level function ```python

    Organize data by colors ( hue )

    sns.lmplot(x=”quality”, y=”alcohol”, data=df, hue=”type”)

Organize data by columns ( col )

sns.lmplot(x=”quality”, y=”alcohol”, data=df, col=”type”)



[seaborn_2_chapter2.pdf](https://www.yuque.com/attachments/yuque/0/2022/pdf/26718834/1649128419283-1f178ea5-6cdb-4182-a450-0f7be43bd66b.pdf)
<a name="xrxxf"></a>
# chapter 2
<a name="oYCJU"></a>
## 1.1 Using Seaborn Styles: sns.set_style()
```python
for style in ['white','dark','whitegrid','darkgrid', 'ticks']: 
    sns.set_style(style) 
    sns.distplot(df['Tuition']) 
    plt.show()

# Removing axes with despine()
sns.set_style('white') 
sns.distplot(df['Tuition']) 
sns.despine(left=True)

1.2 Colors

# using matplotlib color codes
sns.set(color_codes=True) 
sns.distplot(df['Tuition'], color='g')

palettes: set_palette()

for p in sns.palettes.SEABORN_PALETTES: 
    sns.set_palette(p) 
    sns.distplot(df['Tuition'])

image.png

for p in sns.palettes.SEABORN_PALETTES: 
    sns.set_palette(p) 
    sns.palplot(sns.color_palette()) 
    plt.show()
  • Circular colors = when the data is not ordered
  • Sequential colors = when the data has a consistent range from high to low
  • Diverging colors = when both the low and high values are interesting

    sns.palplot(sns.color_palette( "Paired", 12))
    sns.palplot(sns.color_palette( "Blues", 12))
    sns.palplot(sns.color_palette( "BrBG", 12))
    

    1.3 Customizing with matplotlib

  • Most customization available through matplotlib Axes objects

  • Axes can be passed to seaborn functions ```python fig, ax = plt.subplots() sns.distplot(df[‘Tuition’], ax=ax) ax.set(xlabel=”Tuition 2013-14”)

fig, ax = plt.subplots() sns.distplot(df[‘Tuition’], ax=ax) ax.set(xlabel=”Tuition 2013-14”, ylabel=”Distribution”, xlim=(0, 50000), title=”2013-14 Tuition and Fees Distribution”)

Combining Plots

fig, (ax0, ax1) = plt.subplots( nrows=1,ncols=2, sharey=True, figsize=(7,4)) sns.distplot(df[‘Tuition’], ax=ax0) sns.distplot(df.query( ‘State == “MN”‘)[‘Tuition’], ax=ax1) ax1.set(xlabel=”Tuition (MN)”, xlim=(0, 70000)) ax1.axvline(x=20000, label=’My Budget’, linestyle=’—‘) ax1.legend()


[seaborn_2_chapter3.pdf](https://www.yuque.com/attachments/yuque/0/2022/pdf/26718834/1649138974329-7ef3c9fb-7e77-46b1-9070-cded82f265a4.pdf)
<a name="mdoE1"></a>
# chapter 3
<a name="oDPpl"></a>
## 1.1 Categorical Plot Types
**分类散点图:**show each observation

- [**stripplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.stripplot.html?id=seaborn.stripplot)** (with kind="strip"; the default)**
- [**swarmplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.swarmplot.html?id=seaborn.swarmplot)** (with kind="swarm")**

**分类分布图:**abstract representations

- [**boxplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.boxplot.html?id=seaborn.boxplot)** (with kind="box")**
- [**violinplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.violinplot.html?id=seaborn.violinplot)** (with kind="violin")**
- [**boxenplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.boxenplot.html?id=seaborn.boxenplot)** (with kind="boxen")**

**分类估计图:**statistical estimates 

- [**pointplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.pointplot.html?id=seaborn.pointplot)** (with kind="point")**
- [**barplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.barplot.html?id=seaborn.barplot)** (with kind="bar")**
- [**countplot()**](https://seaborn.apachecn.org/#/../generated/seaborn.countplot.html?id=seaborn.countplot)** (with kind="count")**
<a name="dHxKY"></a>
### 1.1.1 stripplot 
```python
sns.stripplot(data=df, y="DRG Definition", x="Average Covered Charges", jitter=True)

image.png

1.1.2 swarmplot

sns.swarmplot(data=df, y="DRG Definition", x="Average Covered Charges")

image.png

1.2.1 boxplot

sns.boxplot(data=df, y="DRG Definition", x="Average Covered Charges")

image.png

1.2.2 violinplot

sns.violinplot(data=df, y="DRG Definition", x="Average Covered Charges")

image.png

1.2.3 boxenplot

sns.boxenplot(data=df, y="DRG Definition", x="Average Covered Charges")

image.png

1.3.1 barplot

sns.barplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region")

image.png

1.3.2 pointplot

sns.pointplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region")

image.png

1.3.3 countplot

sns.countplot(data=df, y="DRG_Code", hue="Region")

image.png

1.2 Regression Plots: regplot() / residplot()

sns.regplot(data=df, x='temp', y='total_rentals', marker='+')
sns.residplot(data=df, x='temp', y='total_rentals')
image.png image.png
似乎不太随机分布,尝试二次拟合。
# Polynomial regression
sns.regplot(data=df, x='temp', y='total_rentals', order=2)
sns.residplot(data=df, x='temp', y='total_rentals', order=2)
image.png image.png
sns.regplot(data=df, x='mnth', y='total_rentals', x_jitter=.1, order=2)

sns.regplot(data=df, x='mnth', y='total_rentals', x_estimator=np.mean, order=2)

# binning the data: divide the data into discrete bins
sns.regplot(data=df,x='temp',y='total_rentals', x_bins=4)
image.png image.png

1.3 Matrix Plots

  • heatmap() function requires data to be in a grid format
  • pandas crosstab() is frequently used to manipulate the data ```python pd.crosstab(df[“mnth”], df[“weekday”],
          values=df["total_rentals"],
          aggfunc='mean').round(0)
    

sns.heatmap(pd.crosstab(df[“mnth”], df[“weekday”], values=df[“total_rentals”], aggfunc=’mean’) )

Customize a heatmap

sns.heatmap(df_crosstab, annot=True, fmt=”d”, cmap=”YlGnBu”, cbar=False, linewidths=.5)

Centering a heatmap

sns.heatmap(df_crosstab, annot=True, fmt=”d”, cmap=”YlGnBu”, cbar=True, center=df_crosstab.loc[9, 6])

Plotting a correlation matrix: Pandas corr function

sns.heatmap(df.corr())


[seaborn_2_chapter4.pdf](https://www.yuque.com/attachments/yuque/0/2022/pdf/26718834/1649152307971-9e89b6c1-8b72-4f44-acbb-d8ee6a11e4da.pdf)
<a name="ARqso"></a>
# chapter 4
<a name="LrP3h"></a>
## 1.1 Using FacetGrid: 三个维度 --- col/row/hue

- It allows the user to control how data is distributed across **columns, rows and hue** 
- Once a FacetGrid is created, the plot type must be **map**ped to the grid
```python
g = sns.FacetGrid(df, col="HIGHDEG") 
g.map(sns.boxplot, 'Tuition', order=['1', '2', '3', '4'])

image.png

g = sns.FacetGrid(df, col="HIGHDEG") 
g.map(plt.scatter, 'Tuition', 'SAT_AVG_ALL')

注:better to use a figure-level function than to use :class:FacetGrid directly.
two steps:

  • Create a FacetGrid object with columns, rows, or hue.
  • Map individual plots to the grid.

    1.2 Using PairGrid —- pairplot()

    ```python

    Creating a PairGrid

    g = sns.PairGrid(iris, vars=[“sepal_length”,”sepal_width”]) g.map(sns.scatterplot)

Customizing the PairGrid diagonals

g = sns.PairGrid(iris, vars=[“sepal_length”,”sepal_width”]) g.map_diag(plt.hist) g.map_offdiag(plt.scatter) plt.show()

| ![image.png](https://cdn.nlark.com/yuque/0/2022/png/26718834/1649162753727-d781d3f9-8bff-4999-99c1-db9a19639989.png#clientId=u3029df3e-cc07-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=372&id=uaff7a5c1&margin=%5Bobject%20Object%5D&name=image.png&originHeight=541&originWidth=603&originalType=binary&ratio=1&rotation=0&showTitle=false&size=82651&status=done&style=none&taskId=ue2144083-9c6c-4e4b-838e-cff91ce9b8c&title=&width=415) | ![image.png](https://cdn.nlark.com/yuque/0/2022/png/26718834/1649162832473-3e0b8d29-68e7-479c-b045-81530c16cb22.png#clientId=u3029df3e-cc07-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=540&id=uc6cb7b13&margin=%5Bobject%20Object%5D&name=image.png&originHeight=540&originWidth=551&originalType=binary&ratio=1&rotation=0&showTitle=false&size=77700&status=done&style=none&taskId=u93a4014a-a873-46c7-8249-541c9e30d91&title=&width=551) |
| --- | --- |

```python
# pairplot is a shortcut for the PairGrid
sns.pairplot(iris, vars=["sepal_length","sepal_width"], kind='reg', diag_kind='hist')
plt.show()

image.png

1.3 Using JointGrid —- JointGrid()

image.png

g = sns.JointGrid(data=df, x="Tuition", y="ADM_RATE_ALL") 
g.plot(sns.regplot, sns.distplot)

g = sns.JointGrid(data=df, x="Tuition", y="ADM_RATE_ALL") 
g = g.plot_joint(sns.kdeplot) 
g = g.plot_marginals(sns.kdeplot, shade=True) 
g = g.annotate(stats.pearsonr)

# jointplot
sns.jointplot(data=df, x="Tuition", y="ADM_RATE_ALL", kind='hex')

# Customizing a jointplot
g = (sns.jointplot(x="Tuition", y="ADM_RATE_ALL", 
                   kind='scatter', xlim=(0, 25000), 
                   marginal_kws=dict( bins=15,rug=True), 
                   data=df.query('UG < 2500 & Ownership == "Public"')) 
     .plot_joint(sns.kdeplot))
image.png image.png
image.png image.png