Code
import seaborn as sns
print(sns.__version__)
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
join plot
make 2 plot per column
sub plot
If you set the set_style function without any arguments the “darkgrid” theme will be used by default, which adds a gray background and white grid lines.
If you want to add gray grid lines but with a white background set this theme.
The “dark” theme is the same as “darkgrid” but without the grid lines.
The “white” theme is the same as “whitegrid” but without the gray grid lines.
The “ticks” theme is the same as the “white” theme but this theme adds ticks to the axes.
from celluloid import Camera
from matplotlib import pyplot as plt
fig = plt.figure()
camera = Camera(fig)
a=sns.lineplot(data=dowjones4,x='Date',y='Price',hue='type')
hands, labs = a.get_legend_handles_labels()
new_data=dowjones4.sample(50, random_state=42)
new_data=new_data.sort_values(by=['Date'], ascending=True)
for i in (new_data["Date"]):
data=dowjones4.query('Date <= @i')
#print(data)
sns.lineplot(data=data,x='Date',y='Price',hue='type')
plt.legend(handles=hands, labels=labs)
camera.snap()
animation = camera.animate()
https://seaborn.pydata.org/index.html
https://www.youtube.com/watch?v=ooqXQ37XHMM
---
title: "seaborn chart"
execute:
warning: false
error: false
eval: false
format:
html:
toc: true
toc-location: right
code-fold: show
code-tools: true
number-sections: true
code-block-bg: true
code-block-border-left: "#31BAE9"
---

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.
```{python}
import seaborn as sns
print(sns.__version__)
```
```{python}
# Import seaborn
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
# Apply the default theme
#sns.set_theme()
# Load an example dataset
tips = sns.load_dataset("tips")
tips.head()
```
# Scatter Plot
```{python}
sns.scatterplot(data=tips,x='tip',y='total_bill')
```
## color by group
```{python}
sns.scatterplot(data=tips,x='tip',y='total_bill',hue='sex')
```
## size by group
```{python}
sns.scatterplot(data=tips,x='tip',y='total_bill',size='size')
```
# line Plot
```{python}
dowjones= sns.load_dataset("dowjones")
dowjones.head()
```
```{python}
sns.lineplot(data=dowjones,x='Date',y='Price')
```
## color by group
```{python}
#| code-fold: true
import random
from siuba import _, mutate, filter, group_by, summarize,show_query
from siuba import *
dowjones2=dowjones>>mutate(type='old')
dowjones3=dowjones>>mutate(Price=_.Price+random.random()*200,type='new')
dowjones4=pd.concat([dowjones2, dowjones3], ignore_index = True)>> arrange(_.Date)
```
```{python}
dowjones4.head()
```
```{python}
sns.lineplot(data=dowjones4,x='Date',y='Price',hue='type')
```
# histogram
```{python}
sns.histplot(data=tips,x='tip')
```
## color by group
```{python}
sns.histplot(data=tips,x='tip',hue='sex',multiple="dodge")
```
# bar chart
```{python}
sns.barplot(data=tips,x='sex',y='tip',errorbar=None)
```
## show number
```{python}
ax=sns.barplot(data=tips,x='sex',y='tip',errorbar=None)
for i in ax.containers:
ax.bar_label(i,)
```
## horizontal bar plot
```{python}
ax=sns.barplot(data=tips,y='sex',x='tip',errorbar=None,orient = 'h')
plt.show()
```
# box plot
```{python}
sns.boxplot(data=tips,x='day',y='tip')
```
## color by group
```{python}
sns.boxplot(data=tips,x='day',y='tip',hue='sex')
```
# strip plot
```{python}
sns.stripplot(data=tips,x='day',y='tip')
```
## color by group
```{python}
sns.stripplot(data=tips,x='day',y='tip',hue='sex',dodge=True)
```
join plot
```{python}
sns.jointplot(data=tips,x='total_bill',y='tip',kind='reg')
```
# Facet plot
```{python}
g = sns.FacetGrid(data=tips, col="day", hue="sex")
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.add_legend()
```
make 2 plot per column
```{python}
g = sns.FacetGrid(data=tips, col="day",col_wrap=2, hue="sex")
g.map_dataframe(sns.scatterplot, x="total_bill", y="tip")
g.add_legend()
```
sub plot
```{python}
#sns.set()
#define plotting region (1 rows, 2 columns)
fig, axes = plt.subplots(1, 2)
sns.boxplot(data=tips,x='day',y='tip',hue='sex',ax=axes[0])
sns.boxplot(data=tips,x='day',y='tip',ax=axes[1])
```
# chinese 显示中文 in Mac
```{python}
# add following line
plt.rcParams['font.family'] = ['Arial Unicode MS'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
sns.set_style('whitegrid',{'font.sans-serif':['Arial Unicode MS','Arial']})
```
# title,size,x y name
## add title
```{python}
df = sns.load_dataset("tips")
ax=sns.boxplot(x = "day", y = "total_bill", data = df)
ax.set_title("tips box plot ")
```
## adjust size
```{python}
plt.clf()
plt.figure(figsize=(10, 6))
ax=sns.boxplot(x = "day", y = "total_bill", data = df)
ax.set_title("tips box plot ")
plt.show()
```
## change x y name
```{python}
ax=sns.boxplot(x = "day", y = "total_bill", data = df)
ax.set_title("tips box plot ")
ax.set(xlabel='x-axis label', ylabel='y-axis label')
```
# applying themes
::: {.panel-tabset .nav-pills}
## darkgrid themes
If you set the set_style function without any arguments the "darkgrid" theme will be used by default, which adds a gray background and white grid lines.
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
sns.set_theme()
# Equivalent to:
# sns.set_style("darkgrid")
sns.boxplot(x = "day", y = "total_bill", data = df)
```
## whitegrid themes
If you want to add gray grid lines but with a white background set this theme.
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
sns.set_style("whitegrid")
sns.boxplot(x = "day", y = "total_bill", data = df)
```
## dark themes
The "dark" theme is the same as "darkgrid" but without the grid lines.
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
sns.set_style("dark")
sns.boxplot(x = "day", y = "total_bill", data = df)
```
## white themes
The "white" theme is the same as "whitegrid" but without the gray grid lines.
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
sns.set_style("white")
sns.boxplot(x = "day", y = "total_bill", data = df)
```
## ticks themes
The "ticks" theme is the same as the "white" theme but this theme adds ticks to the axes.
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
sns.set_style("ticks")
sns.boxplot(x = "day", y = "total_bill", data = df)
```
## fivethirtyeight themes
```{python}
plt.clf()
plt.style.use('fivethirtyeight')
sns.boxplot(x = "day", y = "total_bill", data = df)
plt.show()
```
## ggplot
```{python}
plt.clf()
plt.style.use('ggplot')
sns.boxplot(x = "day", y = "total_bill", data = df)
fig.tight_layout()
plt.show()
```
## tableau-colorblind10
```{python}
plt.clf()
plt.style.use('tableau-colorblind10')
sns.boxplot(x = "day", y = "total_bill", data = df)
fig.tight_layout()
plt.show()
```
## dark_background
```{python}
plt.clf()
plt.style.use('dark_background')
sns.boxplot(x = "day", y = "total_bill", data = df)
fig.tight_layout()
plt.show()
```
:::
# Save plot
```{python}
import seaborn as sns
df = sns.load_dataset("tips")
plt.clf()
plt.style.use('default')
sns.boxplot(x = "day", y = "total_bill", data = df)
# Save the plot with desired size
plt.savefig("output.png", dpi=100, bbox_inches="tight")
```
# Animation plot
```{python}
from celluloid import Camera
```
```{python}
#| output: false
from celluloid import Camera
from matplotlib import pyplot as plt
fig = plt.figure()
camera = Camera(fig)
a=sns.lineplot(data=dowjones4,x='Date',y='Price',hue='type')
hands, labs = a.get_legend_handles_labels()
new_data=dowjones4.sample(50, random_state=42)
new_data=new_data.sort_values(by=['Date'], ascending=True)
for i in (new_data["Date"]):
data=dowjones4.query('Date <= @i')
#print(data)
sns.lineplot(data=data,x='Date',y='Price',hue='type')
plt.legend(handles=hands, labels=labs)
camera.snap()
animation = camera.animate()
```
```{python}
from IPython.display import HTML
HTML(animation.to_html5_video())
```
# reference:
https://seaborn.pydata.org/index.html
https://www.youtube.com/watch?v=ooqXQ37XHMM