- chapter 1
- 1. Matplotlib
- 2. Pandas
- 3. Seaborn
- Organize data by colors ( hue )
- Organize data by columns ( col )
- Combining Plots
- 1.2 Regression Plots: regplot() / residplot()
- 1.3 Matrix Plots
- Customize a heatmap
- Centering a heatmap
- Plotting a correlation matrix: Pandas corr function
- Creating a PairGrid
- Customizing the PairGrid diagonals
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’])
<a name="gfH4Z"></a>## 1.2 Using the distribution plot```python# A kde curve and rug plot can be combinedsns.distplot(df['alcohol'], kde=False, bins=10)sns.distplot(df['alcohol'], hist=False, rug=True)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)

- 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'])

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)
1.1.2 swarmplot
sns.swarmplot(data=df, y="DRG Definition", x="Average Covered Charges")
1.2.1 boxplot
sns.boxplot(data=df, y="DRG Definition", x="Average Covered Charges")
1.2.2 violinplot
sns.violinplot(data=df, y="DRG Definition", x="Average Covered Charges")
1.2.3 boxenplot
sns.boxenplot(data=df, y="DRG Definition", x="Average Covered Charges")
1.3.1 barplot
sns.barplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region")
1.3.2 pointplot
sns.pointplot(data=df, y="DRG Definition", x="Average Covered Charges", hue="Region")
1.3.3 countplot
sns.countplot(data=df, y="DRG_Code", hue="Region")
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')
![]() |
![]() 似乎不太随机分布,尝试二次拟合。 |
|---|---|
# Polynomial regression
sns.regplot(data=df, x='temp', y='total_rentals', order=2)
sns.residplot(data=df, x='temp', y='total_rentals', order=2)
![]() |
![]() |
|---|---|
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)
![]() |
![]() |
|---|---|
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'])

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()
```pythonCreating 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()
|  |  |
| --- | --- |
```python
# pairplot is a shortcut for the PairGrid
sns.pairplot(iris, vars=["sepal_length","sepal_width"], kind='reg', diag_kind='hist')
plt.show()
1.3 Using JointGrid —- JointGrid()

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))
![]() |
![]() |
|---|---|
![]() |
![]() |










