Python

[可视化]汇总:图形属性设置

2020-01-27  本文已影响0人  DDuncan
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sb

一、plt: matplotlib.pyplot

图形对象 知乎@十维教育

整个图像为一个figure对象,在figure对象中可以包含一个或者多个axes,每个axes(ax)对象都是一个拥有自己坐标系统的绘图区域

图形对象 设置参数
Figure plt.figure(num=, figsize=(30, 8))
num:类似窗体的id号,或者说窗体标题
figsize: 以英寸为单位的宽高
suptitle 针对Figure对象,即整个图表
Axes(Subplot) 挨个调用多个 Matplotlib 函数,所有图表都会在同一个坐标轴上绘制plt.axis('square')
plt.axis('equal')将坐标轴比例设置为相等,对角线为 45 度角(Q-Q图)
plt.subplot(1, 2, 1)
plt.figure().add_subplot(111)
Title 针对Axes对象
Labels 标签 plt.xlabel()
plt.ylabel()
('proportion')
Ticks 刻度 plt.xticks()
plt.yticks()
(ticks, [labels], **kwargs, rotation = 90, )
Lims 坐标范围 plt.xlim(0, 35)重点关注(0, 35)区间的图
plt.ylim()
Text plt.text(loc, count-8, pct_string, ha = 'center', color = 'w')
Legend 图例 plt.legend(*args, **kwargs)
(loc=, ncol=)
frameon=False 去掉标签的边框
Scale plt.xscale()
"linear", "log", "symlog", "logit", "symlog"...
log是log10 只允许正值
linear是线性平时默认的那种
logit是0, 1
symlog是对称对数,并允许正值和负值,允许在曲线内设置一个范围在零附近线性而不用对数
其余 plt.colorar(, label= ,)
plt.grid(True)图表带网格
plt.savefig('') 存储图像

plt.show()
plt.plot(xlim=[], ylim=[], 'linestyle', color= )
locs, labels = plt.xticks()
tick_names = ['{:0.2f}'.format(v) for v in tick_props]
plt.gcf()获取当前的图表
plt.gca()获取当前的子图
plt.barh(width,bottom,left,height) 横向柱状图
df.plot.barh(stacked=True,alpha=0.5) 堆积效果
plt.polar(theta,r)极坐标系
plt.psd(x,NFFT=256,pad_to,Fs) 功率谱密度图
plt.specgram(x,NFFT=256,pad_to,F) 谱图
plt.cohere(x,y,NFFT=256,Fs) X-Y相关性函数
plt.step(x,y,where) 步阶图

  • 补充说明:plt.axis()的参数
    Empty 返回当前坐标轴限值
    off 关闭坐标轴线和标签
    equal 使用等刻度
    scaled 通过尺寸变化平衡刻度
    tight 使所有数据可见(缩小限值)
    image 使所有数据可见(使用数据限值)
    [xmin,xmax,ymin,ymax] 将设置限制为给定的(一组)值
  • 获取图形对象
    ax.get_ylim()
    ax.xaxis.get_major_ticks()
    ax.xaxis.get_minor_ticks()
    ax.xaxis.get_major_locator()
    ax.xaxis.get_minor_locator()
    ax.xaxis.get_major_formatter()
    ax.xaxis.get_minor_formatter()
  • 设置图形对象
    ax.spines['right'].set_color('none') 取消右边轴
    ax.spines['top'].set_color('none') 取消上边轴
    ax.xaxis.set_ticks_position('bottom') 设置默认的x轴
    ax.spines['bottom'].set_position('data', -1) 将x轴放在y轴上的-1点处——此时坐标原点为(0, -1)
  • 添加标注Annotation
plt.annotate(r'$2x+1=%s$' %y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontdict={'size':'16', 'color': 'black'})
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$', fontdict={'size': '16', 'color': 'red'})
图形注释
  • 设置坐标刻度的可见度
label = ax.get_xticklabels()
label.set_fontsize(12) #调节字体大小
label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.7)) #设置相关参数 facecolor-前景色;edgecolor-边框;alpha-透明度
设置坐标刻度的可见度
  • 可选参数loc=
    可选参数 loc
  • 设置线条格式 linestyle=
  • 补充:标注参考线
    plt.axvline(data, color, linewidth)
    参考线

二、sb: Seaborn(5大类21种图)

针对统计绘图,一般来说,seaborn能满足数据分析90%的绘图需求

Seaborn可以在Matplotlib的基础上做修改,这意味着可以继承plt.figure()等的设置
注意:Seaborn的图形对象统称为ax 例如ax = sb.boxplot()
(通常 g=sb.FacetGrid(), 此处g与ax完全等价)

图形对象 设置参数
Figure @Matplotlib
Axes(Subplot)
Title
Labels 标签 ax.set_xticklabels()
ax.set_yticklabels()
Ticks 刻度 ax.set_xticks()
ax.set_yticks()
Text
Legend 图例 ax.add_legend()
Scale plt.xscale()
"linear", "log", "symlog", "logit", ...
其余
  • 针对 .FacetGrid()
  1. 实例化对象 ax = sb.FacetGrid()
  2. .map()映射到具体的 seaborn 图表类型
    ax.map() 并非必须是内置函数,可以是plt对象,后续可使用plt对象的属性设置;还可以自定义
  3. 添加图例等信息
  • Seaborn.JointGrid 类
    g = sb.JointGrid()
sb.JointGrid(x, y, data=None, size=6, ratio=5, space=0.2, dropna=True, xlim=None, ylim=None*) 
#用边缘单变量图绘制二元图的网格
.JointGrid()步骤 组合图形
1. 关系类图表 Relational plots
  1. relplot() 关系类图表的接口,指定kind参数可以画出下面2种图
sns.relplot(x="time", y="firing_rate",
            hue="coherence", size="choice", col="align",
            size_order=["T1", "T2"], palette=palette,
            height=5, aspect=.75, facet_kws=dict(sharex=False),
            kind="line", legend="full", data=dots)
多个面上的线图
  1. scatterplot() 散点图
  1. lineplot() 折线图
    所传数据必须为一个pandas数组,这一点跟matplotlib里有较大区别
sb.lineplot(x="timepoint", y="signal",
             hue="region", style="event",
             data=df)
#参数x: 图的x轴label
#参数y: 图的y轴label
#参数ci: 与估计器聚合时绘制的置信区间的大小
#参数data: 所传入的pandas数组
带误差带的时间序列图
data = data.rolling(7).mean()
sns.lineplot(data=data, palette="tab10", linewidth=2.5)
多个数据集的线图
2. 分类图表 Categorical plots
  1. catplot() 分类图表的接口,指定kind参数可以画出下面8种图
g = sb.catplot(x="class", y="survived", hue="sex", data=titanic,
                height=6, kind="bar", palette="muted")
g.despine(left=True)
分组条形图
g = sb.catplot(x="time", y="pulse", hue="kind", col="diet",
                capsize=.2, palette="YlGnBu_d", height=6, aspect=.75,
                kind="point", data=df)
g.despine(left=True)
三路ANOVA
  1. stripplot() 带状图
  1. swarmplot() 蜂群图
  1. boxplot() 箱图
sb.boxplot(x="day", y="total_bill",
            hue="smoker", palette=["m", "g"],
            data=tips)
sns.despine(offset=10, trim=True)
分组箱线图
  1. violinplot() 小提琴图
sb.violinplot(x="day", y="total_bill", hue="smoker",
               split=True, inner="quart",
               palette={"Yes": "y", "No": "b"},
               data=tips)
sns.despine(left=True)
分组小提琴图
  1. boxenplot() 增强箱图
  1. pointplot() 点图
  1. barplot() 条形图
  1. countplot() 计数图
3. 分布图 Distribution plot
  1. jointplot() 双变量关系图
sb.jointplot(x1, x2, kind="kde", height=7, space=0)
联合图
sb.jointplot(x, y, kind="hex", color="#4CB391")

直方图的双变量类似物被称为“hexbin”图,因为它显示了落在六边形仓内的观测数
该图适用于较大的数据集


HexBin图
  1. pairplot() 变量关系组图
  1. distplot() 直方图,质量估计图
sns.distplot(d, kde=False, color="b", ax=axes[0, 0])
sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0, 1])
sns.distplot(d, hist=False, color="g", kde_kws={"shade": True}, ax=axes[1, 0])
sns.distplot(d, color="m", ax=axes[1, 1])
单变量分布的表示方式
  1. kdeplot() 核函数密度估计图
#多个二维kde图
sb.kdeplot(virginica.sepal_width, virginica.sepal_length,
                 cmap="Blues", shade=True, shade_lowest=False)
分布密度
  1. rugplot() 轴须图
4. 回归图 Regression plots
  1. lmplot() 回归模型图
sb.lmplot(x="x", y="y", col="dataset", hue="dataset", data=df,
           col_wrap=2, ci=None, palette="muted", height=4,
           scatter_kws={"s": 50, "alpha": 1})
#参数x, y, data
#参数col, hue
#参数col_wrap 一行显示2个图
#参数ci 
#参数palette 色彩
#参数height 高度
#参数scatter_kws 设置其余参数 透明度等alpha
安斯库姆四重奏
#多元线性回归
sb.lmplot(x="sepal_length", y="sepal_width", hue="species",
               truncate=True, height=5, data=iris)
多元线性回归
#分面逻辑回归
sb.lmplot(x="age", y="survived", col="sex", hue="sex", data=df,
               palette=pal, y_jitter=.02, logistic=True)
分面逻辑回归
  1. regplot() 线性回归图
  1. residplot() 线性回归残差图
sb.residplot(x, y, lowess=True, color="g")
线性回归残差图
5. 矩阵图 Matrix plots
  1. heatmap() 热图
flights = flights_long.pivot("month", "year", "passengers") #数据透视
f, ax = plt.subplots(figsize=(9, 6))
sb.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)
热图
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
            square=True, linewidths=.5, cbar_kws={"shrink": .5})
对角线一半的热图
  1. clustermap() 聚集图
used_networks = [1, 5, 6, 7, 8, 12, 13, 17]
used_columns = (df.columns.get_level_values("network")
                          .astype(int)
                          .isin(used_networks))
df = df.loc[:, used_columns]

network_pal = sns.husl_palette(8, s=.45)
network_lut = dict(zip(map(str, used_networks), network_pal))
networks = df.columns.get_level_values("network")
network_colors = pd.Series(networks, index=df.columns).map(network_lut)

sns.clustermap(df.corr(), center=0, cmap="vlag",
               row_colors=network_colors, col_colors=network_colors,
               linewidths=.75, figsize=(13, 13))
聚集图
6. 分面图 FacetGrid
g = sns.FacetGrid(df, col="speed", hue="speed",
                  subplot_kws=dict(projection='polar'), height=4.5,
                  sharex=False, sharey=False, despine=False)
g.map(sns.scatterplot, "theta", "r")
@迁移:表示能力分布

三、具体操作

1. 坐标尺度变换:对数转换

数据本身log转换+配套坐标尺度转换为对数

log_data = np.log10(data)
plt.xscale('log')
tick_locs = [10, 30, 100, 300, 1000, 3000] 
#按倍数标刻坐标轴(间隔对应相等)
plt.xticks(tick_locs, tick_locs)
2. 调色板
  • 分类:色调不同
    hls
    husl
    Paired
    Set1~Set3
  • 连续:同色系渐变
    Blues[蓝s,颜色+s]
    BuGn[蓝绿]
    cubehelix
  • 离散:双色对称
    BrBG[棕绿]
    RdBu[红蓝]
    coolwarm[冷暖]
  • 颜色代码
    color=' #054E9F' 每两个十六进制数分别代表R、G、B分量
Matplotlib Seaborn
获取 plt.get_cmap()
设置参数 图像的参数cmap=plt.get_cmap('gray_r') sb.color_palette(n_colors=9)
sb.FacetGrid(, palette=, )

seaborn.palplot(sb.color_palette(n_colors=9)) 将颜色调色板中的值绘制为水平数组

调色板显示:水平数组
sb.palplot(sb.hls_palette(8, l=.3, s=.8))
l-亮度 lightness
s-饱和 saturation
调色板参数设置
  • 内置 Matplotlib 调色板
    Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r...其中末尾加r是颜色取反
  • Seaborn扩展增加的调色板
  1. 默认颜色的主题:6种类型
    'deep’
    ’pastel’
    ’dark’
    ’muted’
    ’bright’
    ’colorblind'
  2. 有序
    ’rocket' (white-orange-red-purple-black)
    ’mako' (mint-green-blue-purple-black)
  3. 发散
    ’vlag' (blue-white-red)
    ’icefire' (blue-black-orange)

以热图plt.hist2d()为例,可以在 hist2d 中设置 "cmap" 参数
设置调色板的最简单方式是使用字符串引用内置 Matplotlib 调色板
设置 cmap = 'viridis_r' 可以将默认的 "viridis" 修改为反向的调色板

3 形状标记
  • 线型linestyle
    -
    -.
    --
  • 点型marker
    v
    ^ 三角形
    s 正方形
    *
    H
    +
    X
    D
    O 圆圈
  • 颜色color
    b
    g
    r
    y
    k
    w

四、补充

  1. 参考《利用python进行数据分析第二版》
  • Figures and Subplots(图和子图)
  • Colors, Markers, and Line Styles(颜色,标记物,线样式
  • Ticks, Labels, and Legends(标记,标签,图例)
  • Annotations and Drawing on a Subplot(注释和在subplot上画图)
  • Saving Plots to File(把图保存为文件)
  • matplotlib Configuration(matplotlib设置)

References

官方文档: matplotlib.axes
知乎: Python技能 | Matplotlib数据可视化=sb

上一篇下一篇

猜你喜欢

热点阅读