首页 > 编程语言 >R包:reticulate R对python的接口包

R包:reticulate R对python的接口包

时间:2024-07-08 09:28:36浏览次数:16  
标签:Width reticulate text 接口 dat python black Species color

介绍1

R和python是两种不同的编程语言,前者是统计学家发明并且服务数学统计计算,后者则是最万能的胶水语言。随着大数据时代的到来,两者在数据分析领域存在越来越多的共同点且可以相互使用,为了破解二者的编程壁垒,CRAN收录了具有R接口的python包,从而使得两类语言的数据能共同使用。

reticulate2 是用于Python和R之间协同操作的全套工具,在RRstudio中均可使用;要求Rstudio必须在1.2版本以上;

install.packages("reticulate")
library(reticulate)

特性

  • reticulate 在R中支持多种方式调用python;
  • 实现R和python对象之间的转换;
  • 随意切换不同版本的python;
  • R内使用$调用python对象;
  • python内使用.调用R对象;
  • 使用import函数导入python模块import("os");
  • source_python()获取任何Python脚本;
  • 使用repl_python()交互使用python;

范例

Rpython对同一数据进行可视化,可视化图形包括scatterplotboxplotbarplotheatmap

散点图

R代码

library(dplyr)
library(ggplot2)

iris %>% mutate(Species=factor(Species, levels = c("setosa", "versicolor", "virginica"))) %>%
  ggplot(aes(x=Sepal.Width, y=Petal.Width, color=Species))+
  geom_point()+
  guides(color=guide_legend("", keywidth = .5, keyheight = .5))+
  labs(title = 'Scatter plot')+
  theme_bw()+
  scale_color_manual(values = c("red", "green", "blue"))+
  theme(plot.title = element_text(size = 10, color = "black", face = "bold", hjust = 0.5), 
      axis.title = element_text(size = 10, color = "black", face = "bold"),
      axis.text = element_text(size = 9, color = "black"),
      text = element_text(size = 8, color = "black"),
      strip.text = element_text(size = 9, color = "black", face = "bold"),
      panel.grid = element_blank(),
      legend.position = c(1, 1),
      legend.justification = c(1, 1),
      legend.background = element_rect(fill="white", color = "black"))

Python代码

dat = r.iris  # Python调用R内嵌数据使用r.data
species_map = {'setosa':1, 'versicolor':2, 'virginica':3}
dat['Species'] = dat['Species'].map(species_map)

import numpy as np
import matplotlib.pyplot as plt
# plt.scatter(dat['Sepal.Width'], dat['Petal.Width'], c=dat['Species'],
#      alpha=0.8, edgecolors='none', s=30, label=["1", "2", "3"])
# plt.title('Scatter plot in iris')
# plt.xlabel('Sepal.Width (cm)')
# plt.ylabel('Petal.Width (cm)')
# plt.legend(loc=1)
# plt.show()
 
dat1 = (np.array(dat[dat.Species==1]['Sepal.Width']), 
        np.array(dat[dat.Species==1]['Petal.Width']))
dat2 = (np.array(dat[dat.Species==2]['Sepal.Width']), 
        np.array(dat[dat.Species==2]['Petal.Width']))
dat3 = (np.array(dat[dat.Species==3]['Sepal.Width']), 
        np.array(dat[dat.Species==3]['Petal.Width']))

mdat = (dat1, dat2, dat3)
colors = ("red", "green", "blue")
groups = ("setosa", "versicolor", "virginica")

# step1 build figure background
fig = plt.figure()

# step2 build axis
ax  = fig.add_subplot(1, 1, 1, facecolor='1.0')  

# step3 build figure
for data, color, group in zip(mdat, colors, groups):
  x, y = data
  ax.scatter(x, y, alpha=0.8, c=color, 
      edgecolors='none', s=30, label=group)      

plt.title('Scatter plot')
plt.legend(loc=1)  

# step4 show figure in the screen
plt.show() 

箱形图

R代码

library(dplyr)
library(ggplot2)

iris %>% mutate(Species=factor(Species, levels = c("setosa", "versicolor", "virginica"))) %>%
  ggplot(aes(x=Species, y=Sepal.Width, fill=Species))+
  stat_boxplot(geom = "errorbar", width = .12)+
  geom_boxplot(width = .3, outlier.shape = 3, outlier.size = 1)+
  guides(fill=guide_legend(NULL, keywidth = .5, keyheight = .5))+
  xlab("")+
  theme_bw()+
  scale_fill_manual(values = c("red", "green", "blue"))+
  theme(plot.title = element_text(size = 10, color = "black", face = "bold", hjust = 0.5), 
      axis.title = element_text(size = 10, color = "black", face = "bold"),
      axis.text = element_text(size = 9, color = "black"),
      text = element_text(size = 8, color = "black"),
      strip.text = element_text(size = 9, color = "black", face = "bold"),
      panel.grid = element_blank(),
      legend.position = c(1, 1),
      legend.justification = c(1, 1),
      legend.background = element_rect(fill="white", color = "black"))

Python代码

dat = r.iris  # Python调用R内嵌数据使用r.data
species_map = {'setosa':1, 'versicolor':2, 'virginica':3}
dat['Species'] = dat['Species'].map(species_map)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

dat11 = (np.array(dat[dat.Species==1]['Sepal.Width']))
dat21 = (np.array(dat[dat.Species==2]['Sepal.Width']))
dat31 = (np.array(dat[dat.Species==3]['Sepal.Width']))

mdat2 = (dat11, dat21, dat31)
colors = ("red", "green", "blue")
groups = ("setosa", "versicolor", "virginica")

fig = plt.figure()
axes = fig.add_subplot(facecolor='1.0')
bplot = axes.boxplot(mdat2, patch_artist=True, notch=0, sym='+', vert=1, whis=1.5,
  whiskerprops = dict(linestyle='--',linewidth=1.2, color='black'))

# color
for patch, color in zip(bplot['boxes'], colors):
  patch.set_facecolor(color)

# axes labels
plt.setp(axes, xticks=[1,2,3],
         xticklabels=["setosa", "versicolor", "virginica"])

red_patch = mpatches.Patch(color='red', label='setosa')
green_patch = mpatches.Patch(color='green', label='versicolor')
blue_patch = mpatches.Patch(color='blue', label='virginica')

plt.legend(handles=[red_patch, green_patch, blue_patch], loc=1)

plt.show()

条形图

R代码

library(dplyr)
library(ggplot2)

iris %>% mutate(Species=factor(Species, levels = c("setosa", "versicolor", "virginica"))) %>%
  select(Species, Sepal.Width) %>% group_by(Species) %>%
  summarize(avg=mean(Sepal.Width), n=n(), sd=sd(Sepal.Width), se=sd/sqrt(n)) %>%
  ungroup() %>%
  ggplot(aes(x=Species, y=avg, fill=Species))+
  geom_bar(stat="identity", width=.4, color="black")+
  geom_errorbar(aes(ymin=avg-sd, ymax=avg+sd), width=.15,
                 position=position_dodge(.9), size=1)+
  guides(fill=guide_legend(NULL, keywidth = .5, keyheight = .5))+
  xlab("")+
  ylab("Sepal.Width")+
  scale_y_continuous(breaks=seq(0, 3.5,0.5), limits=c(0, 4.4),expand = c(0,0))+
  theme_bw()+
  scale_fill_manual(values = c("red", "green", "blue"))+
  theme(axis.title = element_text(size = 10, color = "black", face = "bold"),
      axis.text = element_text(size = 9, color = "black"),
      text = element_text(size = 8, color = "black"),
      strip.text = element_text(size = 9, color = "black", face = "bold"),
      panel.grid = element_blank(),
      legend.position = c(1, 1),
      legend.justification = c(1, 1),
      legend.background = element_rect(fill="white", color = "black"))

Python代码

dat = r.iris  # Python调用R内嵌数据使用r.data
species_map = {'setosa':1, 'versicolor':2, 'virginica':3}
dat['Species'] = dat['Species'].map(species_map)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

mean = list(dat['Sepal.Width'].groupby(dat['Species']).mean())
sd   = list(dat.groupby('Species').agg(np.std, ddof=0)['Sepal.Width'])

df = pd.DataFrame({'mean':mean}, index=["setosa", "versicolor", "virginica"])
df.plot(kind='bar', alpha=0.75, rot=0, edgecolor='black', 
        yerr=sd, align='center', ecolor='black', capsize=5,
        color=("red", "green", "blue"),
        ylim=(0.0, 4.4),
        yticks=list(np.arange(0, 4.0, 0.5)))

# xlabel
plt.xlabel('')
plt.ylabel('Sepal.Width')

# legend
red_patch = mpatches.Patch(color='red', label='setosa')
green_patch = mpatches.Patch(color='green', label='versicolor')
blue_patch = mpatches.Patch(color='blue', label='virginica')
plt.legend(handles=[red_patch, green_patch, blue_patch],   # color and group
    loc=1,                # location
    prop={'size': 8})     # size 
plt.show()

心得

初次使用reticulate的感觉还不错,可以比较完美串联R和Python,尤其是在Rmarkdown文件内使用R和Python代码,但缺点也很明显:

  • 运行Python cell没有详细报错信息;
  • 粗略的报错提示行信息不以Rmd文件整体行作为开始;
  • 无法兼容带有汉字的注释信息;
  • 无法像R一样查看python环境下变量;
  • 出错后有时无任何报错信息

根据visual studio code的最新python插件公布情况看,以后vsc可以完美兼容Jupyter notebook格式文件,因此如果想单独使用python但无较好交互编辑器,可以使用vsc的python插件读取ipynb文件3

参考


  1. https://zhuanlan.zhihu.com/p/35049732 ↩︎

  2. https://github.com/rstudio/reticulate ↩︎

  3. https://code.visualstudio.com/docs/python/jupyter-support ↩︎

标签:Width,reticulate,text,接口,dat,python,black,Species,color
From: https://blog.csdn.net/H20230717/article/details/140259180

相关文章

  • [oeasy]python024_vim读取文件_从头复制到尾_撤销_重做_reg_寄存器
    Guido的简历......
  • PHP转Go系列 | ThinkPHP与Gin框架之API接口签名设计实践
    大家好,我是码农先森。回想起以前用模版渲染数据的岁月,那时都没有API接口开发的概念。PHP服务端和前端HTML、CSS、JS代码混合式开发,也不分前端、后端程序员,大家都是全干工程师。随着前后端分离、移动端开发的兴起,用后端渲染数据的开发方式效率低下,已经不能满足业务对需求快速......
  • python+flask计算机毕业设计高校学生实习信息管理(程序+开题+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着高等教育的普及与深化,高校学生实习已成为连接理论与实践、校园与社会的关键桥梁。然而,传统的实习信息管理方式往往依赖于纸质文档或简......
  • python随笔day03
    python面试基础问题lambda表达式基本语法:变量=lambda[参数列表]:表达式(函数代码+返回值)#调用变量()例子如下:#加法求和函数a=lambdaa,b:a+bprint(a(1,2))#3#args元组类型b=lambda*args:argsprint(b('a','b','c','d',10))#('a','b&......
  • Python网络爬虫:Scrapy框架的全面解析
    Python网络爬虫:Scrapy框架的全面解析一、引言        在当今互联网的时代,数据是最重要的资源之一。为了获取这些数据,我们经常需要编写网络爬虫来从各种网站上抓取信息。Python作为一种强大的编程语言,拥有许多用于网络爬虫的工具和库。其中,Scrapy是一个功能强大且灵......
  • CentOS版Linux安装python
    在CentOS系统上安装Python3.8可以通过以下步骤完成:首先,打开终端。下载Python3.8的源代码:wget  https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz解压下载的源码包:cd到Python-3.8.0.tgz的目录tarxzvfPython-3.8.0.tgz安装必要的构建工具和依赖项:sudoyu......
  • Apifox 6月更新|定时任务、内网自部署服务器运行接口定时导入、数据库 SSH 隧道连接
    Apifox新版本上线啦!!! 看看本次版本更新主要涵盖的重点内容,有没有你所关注的功能特性:自动化测试支持设置「定时任务」 支持内网自部署服务器运行「定时导入」数据库均支持通过SSH隧道连接自动化测试数据库操作优化 将Apifox更新至最新版,一起开启全新体验......
  • 【Playwright+Python】系列教程(四)Pytest 插件在Playwright中的使用
    一、命令行使用详解使用Pytest插件在Playwright中来编写端到端的测试。1、命令行执行测试pytest--browserwebkit--headed2、使用pytest.ini文件配置内容如下:[pytest]#RunfirefoxwithUIaddopts=--headed--browserfirefox效果:运行测试类,可以直接可以按照......
  • python 版本对比图片
    importcv2importnumpyasnpimportosdefcalculate_black_pixels_in_sectors(image,sector):#将图像转换为二值图像_,image=cv2.threshold(image,127,255,cv2.THRESH_BINARY_INV)#获取图像尺寸height,width=image.shape#计......
  • 数学建模——层次分析法 AHP(Python代码)
    层次分析法    层次分析法是由美国运筹学家、匹兹堡大学教授T.L.Saaty于20世纪70年代创立的一种系统分析与决策的综合评价方法,是在充分研究了人类思维过程的基础上提出来的,它较合理地解决了定性问题定量化的处理过程。    AHP的主要特点是通过建立递阶层次结......