seaborn_1_chapter1.pdf

chapter1

1.1 Introduction to Seaborn

  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. # Example 1: Scatter plot
  4. height = [62, 64, 69, 75, 66, 68, 65, 71, 76, 73]
  5. weight = [120, 136, 148, 175, 137, 165, 154, 172, 200, 187]
  6. sns.scatterplot(x=height, y=weight)
  7. plt.show()
  8. # Example 2: Create a count plot
  9. gender = ["Female", "Female", "Female", "Female", "Male", "Male", "Male", "Male", "Male", "Male"]
  10. sns.countplot(x=gender)
  11. plt.show()

Count plots: take in a categorical list and return bars that represent the number of list entries per category

1.2 Using pandas with Seaborn

image.png

  1. # Using DataFrames with countplot()
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. df = pd.read_csv("masculinity.csv")
  6. sns.countplot(x="how_masculine", data=df)
  7. plt.show()

1.3 Adding a third variable with hue

  1. import pandas as pd
  2. import seaborn as sns
  3. tips = sns.load_dataset("tips")
  4. tips.head()
  5. # basic scatterplot
  6. sns.scatterplot(x="total_bill", y="tip", data=tips)
  7. plt.show()
  8. # A scatter plot with hue
  9. sns.scatterplot(x="total_bill", y="tip", data=tips, hue="smoker")
  10. plt.show()
  11. # Setting hue order
  12. sns.scatterplot(x="total_bill", y="tip", data=tips, hue="smoker", hue_order=["Yes", "No"])
  13. plt.show()
  14. # specifying hue colors 使用字典传参,自定义颜色标签
  15. hue_colors = {"Yes": "black", "No": "red"}
  16. sns.scatterplot(x="total_bill", y="tip", data=tips, hue="smoker", palette=hue_colors)
  17. plt.show()
  18. # Using hue with count plots
  19. sns.countplot(x="smoker", data=tips, hue="sex")
  20. plt.show()

seaborn_1_chapter2.pdf

chapter 2

1.1 relational plots: scatter plots or line plots —- relplot()

image.png

1.2 subplots

  1. import seaborn as sns
  2. import matplotlib.pyplot as plt
  3. # subplots in columns
  4. sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", col="smoker")
  5. plt.show()
  6. # subplots in rows
  7. sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", row="smoker")
  8. plt.show()
  9. # Subplots in rows and columns
  10. sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", col="smoker", row="time")
  11. plt.show()
  12. # Wrapping columns
  13. sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", col="day", col_wrap=2)
  14. plt.show()
  15. # Ordering columns
  16. sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", col="day", \
  17. col_wrap=2, col_order=["Thur", "Fri", "Sat", "Sun"])
  18. plt.show()

1.3 Customizing scatter plots

# Subgroups with point size
sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", size="size") 
plt.show()

# Point size and hue
sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", size="size", hue="size") 
plt.show()

# Subgroups with point style
sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", hue="smoker", style="smoker") 
plt.show()

# point transparency: Set alpha to be between 0 and 1 
sns.relplot(x="total_bill", y="tip", data=tips, kind="scatter", alpha=0.4) 
plt.show()
image.png image.png
image.png image.png

1.4 Introduction to line plots

Two types of relational plots: scatter plots and line plots

  • Scatter plots: Each plot point is an independent observation.
  • Line plots: Each plot point represents the same “thing”, typically tracked over time. ```python import matplotlib.pyplot as plt import seaborn as sns

line plot: 一个x对应一个点

sns.relplot(x=”hour”, y=”NO_2_mean”, data=air_df_mean, kind=”line”) plt.show()

Subgroups:线图展示分组

sns.relplot(x=”hour”, y=”NO_2_mean”, data=air_df_loc_mean, kind=”line”, style=”location”, hue=”location”, markers=True) plt.show()

Multiple observations per x-value: 一个x值对应多个点,自动汇总

sns.relplot(x=”hour”, y=”NO_2”, data=air_df, kind=”scatter”) plt.show()

sns.relplot(x=”hour”, y=”NO_2”, data=air_df, kind=”line”) plt.show()

sns.relplot(x=”hour”, y=”NO_2”, data=air_df, kind=”line”, ci=”sd”) plt.show() # 将置信区间替换成标准偏差

sns.relplot(x=”hour”, y=”NO_2”, data=air_df, kind=”line”, ci=None) plt.show() # 关闭置信区间显示


[seaborn_1_chapter3.pdf](https://www.yuque.com/attachments/yuque/0/2022/pdf/26718834/1648902304864-e32e5be2-24cd-46f3-a264-d2de179122fc.pdf)
<a name="qQ2pW"></a>
# chapter 3
<a name="ygjue"></a>
## 1.1 Count plots and bar plots: catplot()
**Categorical plots:count plots **and **bar plots**

- Involve a categorical variable 
- Comparisons between groups 
```python
## count plots
# countplot vs. catplot
sns.countplot(x="how_masculine", data=masculinity_data) 
plt.show()

sns.catplot(x="how_masculine", data=masculinity_data, kind="count") 
plt.show()

# Changing the order
category_order = ["No answer", "Not at all", "Not very", "Somewhat", "Very"] 
sns.catplot(x="how_masculine", 
            data=masculinity_data, 
            kind="count", 
            order=category_order) 
plt.show()

## Bar plots: Lines show 95% con,dence intervals for the mean
sns.catplot(x="day", y="total_bill", data=tips, kind="bar") 
plt.show()

# Changing the orientation
sns.catplot(x="total_bill", y="day", data=tips, kind="bar") 
plt.show()

1.2 box plot

sns.catplot(x="time", y="total_bill", data=tips, kind="box")
plt.show()

# change the order of categories
sns.catplot(x="time", y="total_bill", 
            data=tips, kind="box", 
            order=["Dinner", "Lunch"]) 
plt.show()

# Omitting the outliers using `sym`
sns.catplot(x="time", y="total_bill", 
            data=tips, kind="box", 
            sym="")
plt.show()

# Changing the whiskers using `whis`
# By default, the whiskers extend to 1.5 * the interquartile range 
# Make them extend to 2.0 * IQR: whis=2.0 
# Show the 5th and 95th percentiles: whis=[5, 95] 
# Show min and max values: whis=[0, 100]

1.3 point plots

  • Points show mean of quantitative variable
  • Vertical lines show 95% condence intervals

image.pngimage.png

sns.catplot(x="age", y="masculinity_important", 
            data=masculinity_data, 
            hue="feel_masculine", kind="point") 
plt.show()

# Disconnecting the points
sns.catplot(x="age", y="masculinity_important", 
            data=masculinity_data, 
            hue="feel_masculine", 
            kind="point", join=False) 
plt.show()

# Displaying the median
sns.catplot(x="smoker", y="total_bill", 
            data=tips, kind="point", 
            estimator=median) 
plt.show()

# Customizing the confidence intervals
sns.catplot(x="smoker", y="total_bill", 
            data=tips, kind="point", 
            capsize=0.2) 
plt.show()

seaborn_1_chapter4.pdf

chapter 4

1.1 Changing plot style and color

1.1.1 Changing the figure style :background and axes —- sns.set_style()

  • Preset options: “white”, “dark”, “whitegrid”, “darkgrid”, “ticks”

    # Default figure style ("white")
    sns.set_style("whitegrid")
    sns.set_style("ticks")
    sns.set_style("dark")
    sns.set_style("darkgrid")
    

    1.1.2 Changing the palette:color of the elements in plot —- sns.set_palette()

  • Use preset palettes or create a custom palette

image.png
image.png

sns.set_palette("RdBu")

# custom palettes
custom_palette = ["red", "green", "orange", "blue", "yellow", "purple"] 
sns.set_palette(custom_palette)

1.1.3 Changing the scale : scale of plot elements and labels — sns.set_context()

  • Smallest to largest: “paper”, “notebook”, “talk”, “poster”
    # Default context: "paper"
    sns.set_context("talk")
    

    1.2 Adding titles and labels

    Seaborn plots create two different types of objects: FacetGrid and AxesSubplot
    g = sns.scatterplot(x="height", y="weight", data=df) 
    type(g)
    
    image.png
    image.png

    1.2.1 Adding a title to FacetGrid : g.fig.suptitle()

    ```python g = sns.catplot(x=”Region”, y=”Birthrate”, data=gdp_data, kind=”box”) g.fig.suptitle(“New Title”) plt.show()

Adjusting height of title in FacetGrid

g.fig.suptitle(“New Title”, y=1.03)

<a name="Yot0Q"></a>
### 1.2.2 Adding a title to AxesSubplot 
![image.png](https://cdn.nlark.com/yuque/0/2022/png/26718834/1648964429544-2a982b7a-4bf1-4631-8e5c-d1e40a576c08.png#clientId=u9cf99bab-06a5-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=358&id=u6e3f73eb&margin=%5Bobject%20Object%5D&name=image.png&originHeight=358&originWidth=1169&originalType=binary&ratio=1&rotation=0&showTitle=false&size=45377&status=done&style=none&taskId=u49b70b98-002e-49a8-adcb-9a070e26dbd&title=&width=1169)
```python
# Adding Titles for subplots
g = sns.catplot(x="Region", y="Birthrate", data=gdp_data,  kind="box", col="Group") 

g.fig.suptitle("New Title", y=1.03)               # 整个图的标题

g.set_titles("This is {col_name}")    # 子图标题

1.2.3 Adding axis labels

g = sns.catplot(x="Region", y="Birthrate", data=gdp_data, kind="box") 
g.set(xlabel="New X Label", ylabel="New Y Label") 
plt.show()

# Rotating x-axis tick labels
plt.xticks(rotation=90)

1.2.4 Adding a third variable

  • as a subgroups: hue
  • as a subplots: col/row