首页 > 其他分享 >[seaborn] seaborn学习笔记7 常用参数调整Adjustment of Common Parameters

[seaborn] seaborn学习笔记7 常用参数调整Adjustment of Common Parameters

时间:2022-12-18 22:11:08浏览次数:63  
标签:plt Parameters seaborn df add sns np data Common

date: 2019-06-01 15:26:17 +0800
tags:
  - seaborn
  - Python
  - 数据分析与可视化

7 常用参数调整Adjustment of Common Parameters(代码下载)

主要讲述关于seaborn通用参数设置方法,该章节主要内容有:

  1. 主题设置 themes adjustment
  2. 颜色设置 Manage colors
  3. 轴的管理 Manage axis
  4. 边距调整 Manage margins
  5. 添加注释 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')

png

# 白色网格 whitegrid
sns.set_style("whitegrid")
sns.boxplot(data=data);
plt.title("whitegrid")
Text(0.5, 1.0, 'whitegrid')

png

# 黑色 dark
sns.set_style("dark")
sns.boxplot(data=data);
plt.title("dark")
Text(0.5, 1.0, 'dark')

png

# 白色 white
sns.set_style("white")
sns.boxplot(data=data);
plt.title("white")
Text(0.5, 1.0, 'white')

png

# 十字叉 ticks
sns.set_style("ticks")
sns.boxplot(data=data);
plt.title("ticks")
Text(0.5, 1.0, 'ticks')

png

2. 颜色设置 Manage colors

由于Seaborn是在matplotlib之上构建的,因此Matplotlib上的大部分定制工作也适用于seaborn。seaborn中通过palette选择颜色。可用颜色有:

seaborn有三种类型的调色板: Sequential, Diverging and Discrete:
Sequential
Diverging
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");

png

png

# 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");

png

png

# 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);

png

png

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

png

# 标尺 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)

png

# 标签 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')

png

# 坐标轴范围 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);

png

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!");

png

# 上下边距调整
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)

png

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

png

# 添加长方形 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')
);

png

# 添加圆 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')
);

png

# 添加参考线 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');

png

# 添加公式 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);

png

标签:plt,Parameters,seaborn,df,add,sns,np,data,Common
From: https://www.cnblogs.com/luohenyueji/p/16991060.html

相关文章

  • [seaborn] seaborn学习笔记2 散点图Scatterplot
    2散点图Scatterplot(代码下载)散点图能够显示2个维度上2组数据的值。每个点代表一个观察点。X(水平)和Y(垂直)轴上的位置表示变量的值。研究这两个变量之间的关系是非常有用......
  • [seaborn] seaborn学习笔记1 箱形图Boxplot
    1箱形图Boxplot(代码下载)Boxplot可能是最常见的图形类型之一。它能够很好表示数据中的分布规律。箱型图方框的末尾显示了上下四分位数。极线显示最高和最低值,不包括异常......
  • [seaborn] seaborn学习笔记0 seaborn学习笔记章节
    date:2019-05-2815:54:37+0800tags:-seaborn-Python-数据分析与可视化seaborn学习笔记章节seaborn是一个基于matplotlib的Python数据......
  • 前端开发系列119-进阶篇之commonJS规范和require函数加载的过程
    title:前端开发系列119-进阶篇之commonJS规范和require函数加载的过程tags:categories:[]date:2019-04-1500:00:08今晚接到个面试电话,被问到node中require函数......
  • Pset_BuildingSystemCommon
    Pset_BuildingSystemCommon建筑系统定义的通用特性  NameTypeDescriptionReferenceP_SINGLEVALUE / IfcIdentifierKennzeichenKennzeichenfürdiese......
  • Pset_ChimneyCommon
    Pset_ChimneyCommon烟囱所有引用对象和类型对象定义的公共特性 NameTypeDescriptionReferenceP_SINGLEVALUE / IfcIdentifierBauteiltypBezeichnungzur......
  • 深度学习入门No module named 'common'问题
    这⾥的“common”模块是源代码中作者⾃⼰写的,将下载的源⽂件夹“【源代码】深度学习⼊门:基于Python的理论与实现”改名为book_code,并且将sys.path.append(os.pardir)#......
  • 最大公约数 GCD greatest common divisor
     辗转相除法#include<stdio.h>intmain(void){intm,n,r;scanf("%d%d",&m,&n);if(m<n){m=m^n;n=m^n;......
  • 创建Maven项目与common模块
    1、创建Maven项目下面,我们正式开始开发项目。首先,创建一个Maven项目作为微服务的父工程,将其命名为“mall”。如图所示。  创建好后,编辑pom.xml文件,如程序清单15-1......
  • commonJS, AMD, CMD区别表格对比
    1、对比总览  名称    同步/异步   规范文件 应用场景加载速度描述commonJS同步CommonJSNODEJS平均加载速度最慢最早版本的js模块化编程规范......