7 常用參數調整Adjustment of Common Parameters(代碼下載)
主要講述關於seaborn通用參數設置方法,該章節主要內容有:
- 主題設置 themes adjustment
- 顏色設置 Manage colors
- 軸的管理 Manage axis
- 邊距調整 Manage margins
- 添加註釋 Add annotations
1. 主題設置 themes adjustment
- 灰色網格 darkgrid
- 白色網格 whitegrid
- 黑色 dark
- 白色 white
- 十字叉 ticks
# Seaborn中有五種可供選擇的主題下面通過set_style設置主題
# Proposed themes: darkgrid, whitegrid, dark, white, and ticks
# Data
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
# 灰色網格 darkgrid
sns.set_style("darkgrid")
sns.boxplot(data=data)
plt.title("darkgrid")
Text(0.5, 1.0, 'darkgrid')
# 白色網格 whitegrid
sns.set_style("whitegrid")
sns.boxplot(data=data);
plt.title("whitegrid")
Text(0.5, 1.0, 'whitegrid')
# 黑色 dark
sns.set_style("dark")
sns.boxplot(data=data);
plt.title("dark")
Text(0.5, 1.0, 'dark')
# 白色 white
sns.set_style("white")
sns.boxplot(data=data);
plt.title("white")
Text(0.5, 1.0, 'white')
# 十字叉 ticks
sns.set_style("ticks")
sns.boxplot(data=data);
plt.title("ticks")
Text(0.5, 1.0, 'ticks')
2. 顏色設置 Manage colors
由於Seaborn是在matplotlib之上構建的,因此Matplotlib上的大部分定製工作也適用於seaborn。seaborn中通過palette選擇顏色。可用顏色有:
seaborn有三種類型的調色板: Sequential, Diverging and Discrete:
# Sequential顏色調用
# Libraries
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create data
x = np.random.rand(80) - 0.5
y = x+np.random.rand(80)
z = x+np.random.rand(80)
df = pd.DataFrame({'x':x, 'y':y, 'z':z})
# Plot with palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues");
# reverse palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="Blues_r");
# Diverging顏色調用
# plot
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="PuOr");
# reverse palette
sns.lmplot( x='x', y='y', data=df, fit_reg=False, hue='x', legend=False, palette="PuOr_r");
# Discrete顏色調用
# library & dataset
import seaborn as sns
df = sns.load_dataset('iris')
# --- Use the 'palette' argument of seaborn
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False, palette="Set1");
plt.legend(loc='lower right')
# --- Use a handmade palette 自定義顏色板
flatui = ["#9b59b6", "#3498db", "orange"]
sns.set_palette(flatui)
sns.lmplot( x="sepal_length", y="sepal_width", data=df, fit_reg=False, hue='species', legend=False);
3. 軸的管理 Manage axis
- 標題 Title
- 標尺 Ticks
- 標籤 labels
- 座標軸範圍 limit
# 標題 Title
# Basic plot
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# data
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
y_pos = np.arange(len(bars))
sns.barplot(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
# Custom Axis title 需要調用matplotlib設置軸標題
plt.xlabel('title of the xlabel', fontweight='bold', color = 'orange', fontsize='17', horizontalalignment='center');
# 標尺 Ticks
sns.barplot(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
# Custom ticks 調用matplotlib tick_params控制標尺
plt.tick_params(axis='x', colors='red', direction='out', length=15, width=5)
# You can remove them:
# plt.tick_params(bottom=False)
# 標籤 labels
sns.barplot(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
# use the plt.xticks function to custom labels
plt.xticks(y_pos, bars, color='orange', rotation=45, fontweight='bold', fontsize='17', horizontalalignment='right');
# remove labels
# plt.tick_params(labelbottom='off')
# 座標軸範圍 limit
sns.barplot(y_pos, height, color=(0.2, 0.4, 0.6, 0.6))
# Set the limit
plt.xlim(0,20);
plt.ylim(0,50);
4. 邊距調整 Manage margins
y_pos = np.arange(len(bars))
bars = ('A','B','C','D','E')
height = [3, 12, 5, 18, 45]
sns.barplot(y_pos, height);
# If we have long labels, we cannot see it properly 當名字太長我們無法閱讀
names = ("very long group name 1","very long group name 2","very long group name 3","very long group name 4","very long group name 5")
plt.xticks(y_pos, names, rotation=90);
# It's the same concept if you need more space for your titles
plt.title("This is\na very very\nloooooong\ntitle!");
# 上下邊距調整
sns.barplot(y_pos, height);
# If we have long labels, we cannot see it properly 當名字太長我們無法閱讀
names = ("very long group name 1","very long group name 2","very long group name 3","very long group name 4","very long group name 5")
plt.xticks(y_pos, names, rotation=90);
# It's the same concept if you need more space for your titles
plt.title("This is\na very very\nloooooong\ntitle!")
# Thus we have to give more margin 通過subplots_adjust調整上下區域所佔範圍
plt.subplots_adjust(bottom=0.4)
plt.subplots_adjust(top=0.7)
5. 添加註釋 Add annotations
- 添加文本 add text
- 添加長方形 add rectangle
- 添加圓 add circle
- 添加參考線 add reference line
- 添加公式 add formula
# 添加文本 add text
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })
sns.regplot( data=df, x="x", y="y", marker='o')
# Annotate with text + Arrow 添加文本和箭頭
plt.annotate(
# Label and coordinate
# xy箭頭尖的座標,xytest文本起始位置
'This point is interesting!', xy=(20, 40), xytext=(0, 80),
# Custom arrow 添加箭頭
arrowprops=dict(facecolor='black', shrink=0.05)
);
C:\ProgramData\Anaconda3\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
return np.add.reduce(sorted[indexer] * weights, axis=axis) / sumval
# 添加長方形 add rectangle
# libraries
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Data 數據
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })
# Plot
fig1 = plt.figure()
# 添加子圖
ax1 = fig1.add_subplot(111)
sns.regplot( data=df, x="x", y="y", marker='o')
# Add rectangle 添加長方形
ax1.add_patch(
patches.Rectangle(
(20, 25), # (x,y) 左上角座標
50, 50, # width and height 寬高
# You can add rotation as well with 'angle'
alpha=0.3, facecolor="red", edgecolor="black", linewidth=3, linestyle='solid')
);
# 添加圓 add circle
# Data
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })
# Plot
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
sns.regplot( data=df, x="x", y="y", marker='o')
# Annotation
ax1.add_patch(
patches.Circle(
(40, 35), # (x,y) 圓心
30, # radius 半徑
alpha=0.3, facecolor="green", edgecolor="black", linewidth=1, linestyle='solid')
);
# 添加參考線 add reference line
# Plot
sns.regplot( data=df, x="x", y="y", marker='o')
# Annotation
# 添加垂直參考線
plt.axvline(40, color='r');
# 添加水平參考系
plt.axhline(50, color='green');
# 添加公式 add formula
df=pd.DataFrame({'x': range(1,101), 'y': np.random.randn(100)*15+range(1,101) })
sns.regplot( data=df, x="x", y="y", marker='o')
# Annotation
plt.text(40, 00, r'equation: $\sum_{i=0}^\infty x_i$', fontsize=20);