Python与R共舞:在python中用ggplot2、plotnine画散点相关(回归)分析图(附最新高清plotnine、ggplot2速查表(ggplot2-cheatsheet))

Python与R共舞:在python中用ggplot2、plotnine画散点相关(回归)分析图(附最新高清plotnine、ggplot2速查表(ggplot2-cheatsheet))_第1张图片
| 图源

  虽然python有许多可视化的包,如matplotlib,seaborn,pandas等。但是笔者还是被ggplot2包绘图所吸引,图层直接简单叠加型设计,用它们可以美观、灵活、简洁的构建几乎任何类型的图表。ggplot2有直接的python版本——ggplot(几年未更新,有些地方会与现在的包不兼容),plotnine(一个类似ggplot2的包,但是功能太不齐全)。考虑到ggplot2的python版本存在一些问题,加上还不能和ggplot2辅助包如ggpubr等连用,所以笔者还折腾了一下rpy2。rpy2是一个连接R与python的接口,通过它,我们可以在python代码里直接用R包。最后,对于python里使用ggplot2,折腾了半天,最后实际的感受是,图好看,自由度大,可以用但是接口体验感不佳。

copyright © 意疏:https://blog.csdn.net/sinat_35907936/article/details/120315347


plotnine


  • 安装plotnine

pip install plotnine
  • 使用plotnine画散点相关(回归)分析图

  基本框架:先创建一个ggplot对象,然后在上面叠加+图层。

  plotnine.ggplot:创建ggplot对象,参数包括pandas.DataFrame类型的数据和要分析的变量。相当于创建了一个空白的底层。

  geom_point:添根据数据添加几何点图层。

  stat_smooth:画出回归线与置信区间。

  theme_bw: 设置主题样式:黑色网格线(b)白色背景(w)。

  annotate:添加标注。

import numpy as np
import pandas as pd
import scipy as sp
from plotnine import *

# 模拟数据
x = np.arange(1,100,1)
y = 0.5*x + np.random.randint(low=-1, high=50, size=99)
df = pd.DataFrame({
     'X':x, 'Y':y})

# 计算相关系数
r, p = sp.stats.pearsonr(x, y)
p_text =  'R={:.2f}, P={:.2e}'.format(r, p)

# 画图
p1 = (
    ggplot(df, aes('X', 'Y'))
    + geom_point(colour = "#4682B4", fill = "#87CEFA", size=1)
    + annotate('text', x=2, y=95, label=p_text, ha='left', size=9, color='black')
    + stat_smooth(method='lm', color="#6495ED",fill="#D3D3D3")
    + theme_bw()
)

# 保存图
ggsave(p1, '123.jpg', width=20, height=10, units='cm',dpi=300)

Python与R共舞:在python中用ggplot2、plotnine画散点相关(回归)分析图(附最新高清plotnine、ggplot2速查表(ggplot2-cheatsheet))_第2张图片

  如果出现以下错误:降低scipy版本

Could not find module ‘C:\software\anaconda\lib\site-packages\scipy.libs\libbanded5x.UGR6EUQPIWHQH7SL62IWIXB5545VDNQZ.gfortran-win_amd64.dll’ (or one of its dependencies). Try using the full path with constructor syntax.

pip uninstall scipy
pip install scipy==1.6.1

copyright © 意疏:https://blog.csdn.net/sinat_35907936/article/details/120315347


ggplot2


  • 安装R

  与python一样,R解释器可以通过exe安装,也可以通过conda安装,后者安装的版本要旧许多,但是方便管理起见,还是采用conda安装。

  先添加与R相关的镜像源:

conda config --add channels https://mirrors.ustc.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
conda config --set show_channel_urls yes

  安装R

conda install R

  批量安装常用的R科学计算包

conda install -c r r-essentials

  在系统高级设置->环境变量里添加R_HOME环境变量,变量值填R的安装目录。保险起见可以在系统变量和用户变量里面都添加一个R_HOME变量。

Python与R共舞:在python中用ggplot2、plotnine画散点相关(回归)分析图(附最新高清plotnine、ggplot2速查表(ggplot2-cheatsheet))_第3张图片

  • 安装rpy2

  rpy2是连接python与R的桥梁,只是个接口,所以要先把R装好,配置好才能使用它。之前换好源了,rpy2应该很容易可以装好。

conda install -c r rpy2

测试rpy2与R,如果可以顺利导入,则R与rpy2都没有问题。

import rpy2.robjects as ro

  如果出现:则是R的环境变量没有设置好。

An error ocurred while starting the kernel. R HOME must be set in the environment or Registry
OSError: cannot load library ‘C:\Program Files\R\R-4.0.2\bin\x64\R.dll’: error 0x7e

  • 安装ggpubr

  ggplot2已经在前面被安装过了,这里只安装ggpubr。

conda install -c r r-essentials
  • ggplot2与ggpubr画散点相关(回归)分析图

  图形可以是交互式的,例如X11,或非交互式,如png或pdf,rpy2官网给的显示方式是交互式的,会另外弹出一个窗口,且会阻断程序运行。而下面代码是让图表内嵌在IPython Notebook的页面中,而不是单独弹出一个界面:参考。

from IPython.core.display import Image
from rpy2.robjects.packages import importr
grdevices = importr('grDevices')

def ggplot_notebook(gg, width = 2000, height = 1200):
    # 设置保存图像的格式与分辨率等
    fn = '{name}.jpeg'.format(name = 1234)  
    grdevices.jpeg(fn, width = width, height = height, res=300)
    gg.plot()
    grdevices.dev_off()
    return Image(filename=fn)

  创建仿真数据,先转换成pandas的DataFrame,再转成R的DataFrame。

import numpy as np
import pandas as pd
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
import rpy2.robjects as ro

x = np.arange(1,100,1)
y = 0.5*x + np.random.randint(low=-1, high=50, size=99)
df = pd.DataFrame({
     'X':x, 'Y':y})

# 将pandas转成R的DataFrame
with localconverter(ro.default_converter + pandas2ri.converter):
      r_from_pd_df = ro.conversion.py2rpy(df)

  绘图,基本函数与plotnine类似,只是参数更丰富一些,也就意味着更丰富的绘图结果。
  ggpubr.stat_cor:计算相关并显示

# robjects是rpy2提供的高级接口,里面直接已经有ggplot2,应该是被改写过的,不能使用ggsave
# importr用来导入R库

import rpy2.robjects as ro
from rpy2.robjects.packages import importr
import rpy2.robjects.lib.ggplot2 as ggplot2

grdevices = importr('grDevices')
base = importr('base')
ggpubr = importr('ggpubr')
    
p1=(
      ggplot2.ggplot(r_from_pd_df) + 
      ggplot2.aes_string(x='X', y='Y') + 
      ggplot2.geom_point(shape = 21, colour = "#4682B4", fill = "#87CEFA", size = 2, stroke = .5,alpha=0.8)+
      ggplot2.geom_smooth(method="lm",linetype=2,color="#6495ED",fill="#D3D3D3") +
      ggplot2.theme_bw()+
      ggpubr.stat_cor()
)

ggplot_notebook(p1)

Python与R共舞:在python中用ggplot2、plotnine画散点相关(回归)分析图(附最新高清plotnine、ggplot2速查表(ggplot2-cheatsheet))_第4张图片

copyright © 意疏:https://blog.csdn.net/sinat_35907936/article/details/120315347


ggplot2速查表


  • 2021年8月更新的ggplot2速查表

  • 2016年版ggplot2速查表

  • plotnine速查表

  《python数据可视化之美》作者张杰提供

参考


  https://www.jb51.net/article/63729.html
  https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzkyODIyOTY5Ng==&action=getalbum&album_id=1871868632998215682&scene=173&from_msgid=2247484984&from_itemidx=1&count=3&nolastread=1#wechat_redirect

你可能感兴趣的:(数据分析与数据挖掘,rpy2,ggplot2,plotnine,python与R共舞,回归(相关)分析图)