前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言基础5(绘图基础)

R语言基础5(绘图基础)

原创
作者头像
Erics blog
修改2023-09-23 21:38:41
3230
修改2023-09-23 21:38:41
举报
文章被收录于专栏:R语言数据分析R语言数据分析

常用可视化R包和函数

1,作图

base

ggplot2

ggpubr

2,拼图

par里的mfrow

grid.arrange

cowplot

patchwork

3,导出

经典三段论

ggsave

eoffice——topptx

绘图

基础包

代码语言:text
复制
plot(iris[,1],iris[,3],col = iris[,5]) 
text(6.5,4, labels = 'hello')

dev.off() #关闭画板

ggplot2

代码语言:text
复制
library(ggplot2)
#1.入门级绘图模板:作图数据,横纵坐标
ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length))
#列名不添加引号
#两个函数用+连接

#2.属性设置(颜色、大小、透明度、点的形状,线型等)

#2.1 手动设置,需要设置为有意义的值

ggplot(data = iris) + 
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length), 
             color = "blue")

ggplot(data = iris) + 
  geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length), 
             size = 5,     # 点的大小5mm
             alpha = 0.5,  # 透明度 50%
             shape = 8)  # 点的形状

##颜色:字符串,blue, red等;


#2.2 映射:按照数据框的某一列来定义图的某个属性
ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species))

#color是aes的参数,则选列名,color是geom_point的参数则为具体颜色;

## Q1 能不能自行指定映射的具体颜色?

ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species))+
  scale_color_manual(values = c("blue","grey","red"))

## Q2 区分color和fill两个属性
### Q2-1 空心形状和实心形状都用color设置颜色
ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species),
             shape = 17) #17号,实心的例子

ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species),
             shape = 2) #2号,空心的例子
### Q2-2 既有边框又有内心的,才需要color和fill两个参数

ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species),
             shape = 24,
             fill = "black") #24号,双色的例子

#3.分面
ggplot(data = iris) + 
  geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) + 
  facet_wrap(~ Species) 
#双分面
dat = iris
dat$Group = sample(letters[1:5],150,replace = T)
###新增一列,sample表示抽样;

ggplot(data = dat) + 
  geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) + 
  facet_grid(Group ~ Species) 

#4.几何对象

#局部设置和全局设置

ggplot(data = iris) + 
  geom_smooth(mapping = aes(x = Sepal.Length, 
                          y = Petal.Length))+
  geom_point(mapping = aes(x = Sepal.Length, 
                           y = Petal.Length))
###局部设置
ggplot(data = iris,mapping = aes(x = Sepal.Length, y = Petal.Length))+
  geom_smooth()+
  geom_point()
###全局设置

#5.统计变换-条形图
View(diamonds)
table(diamonds$cut)

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut))

ggplot(data = diamonds) + 
  stat_count(mapping = aes(x = cut))

#统计变换使用场景
#5.1.不统计,数据直接做图
fre = as.data.frame(table(diamonds$cut))
fre

ggplot(data = fre) +
  geom_bar(mapping = aes(x = Var1, y = Freq), stat = "identity")

#5.2count改为prop(比例))
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, y = after_stat(prop), group = 1))


#6.位置关系

# 6.1抖动的点图
ggplot(data = iris,mapping = aes(x = Species, 
                                 y = Sepal.Width,
                                 fill = Species)) + 
  geom_boxplot()+
  geom_point()

ggplot(data = iris,mapping = aes(x = Species, 
                                 y = Sepal.Width,
                                 fill = Species)) + 
  geom_boxplot()+
  geom_jitter()

# 6.2 条形图
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut,fill=clarity))

ggplot(data = diamonds) +
  geom_bar(mapping = aes(x = cut,fill = clarity),
           position = "fill")

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), 
           position = "dodge")

#7.坐标系

bar <- ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = cut),
           width = 1) + 
  theme(aspect.ratio = 1) +
  labs(x = NULL, y = NULL)
bar
bar + coord_flip()#翻转coord_flip()
bar + coord_polar()#极坐标系coord_polar()

作业

代码语言:text
复制
library(ggplot2)
ggplot(data = iris)+
  geom_violin(mapping = aes(x = Species,
                           y = Sepal.Width,
                           fill = Species))+
  scale_color_manual(values = c("pink","green","blue"))+
  geom_boxplot(mapping = aes(x = Species,
                             y = Sepal.Width))+
  geom_jitter(mapping = aes(x = Species,
                            y = Sepal.Width,
              shape=Species))+
  coord_flip()

library(ggplot2)
ggplot(data = iris,aes(x = Species,
                       y = Sepal.Width))+
  geom_violin(aes(fill = Species))+
  scale_color_manual(values = c("pink","green","blue"))+
  geom_boxplot()+
  geom_jitter(aes(shape=Species))+
  coord_flip()

ggpubr

代码语言:text
复制
# ggpubr 搜代码直接用,基本不需要系统学习

# sthda上有大量ggpubr出的图
library(ggpubr)
ggscatter(iris,x="Sepal.Length",
          y="Petal.Length",
          color="Species")

p <- ggboxplot(iris, x = "Species", 
               y = "Sepal.Length",
               color = "Species", 
               shape = "Species",
               add = "jitter")
p
my_comparisons <- list( c("setosa", "versicolor"), 
                        c("setosa", "virginica"), 
                        c("versicolor", "virginica") )
p + stat_compare_means(comparisons = my_comparisons)+ # Add pairwise comparisons p-value
  stat_compare_means(label.y = 9) 

图片保存

代码语言:text
复制
#1.基础包作图的保存
pdf("iris_box_ggpubr.pdf")
boxplot(iris[,1]~iris[,5])
text(6.5,4, labels = 'hello')
dev.off()

#2.ggplot系列图(包括ggpubr)通用的简便保存 ggsave
p <- ggboxplot(iris, x = "Species", 
               y = "Sepal.Length",
               color = "Species", 
               shape = "Species",
               add = "jitter")
ggsave(p,filename = "iris_box_ggpubr.png")

#3.eoffice包 导出为ppt,全部元素都是可编辑模式
library(eoffice)
topptx(p,"iris_box_ggpubr.pptx")
###超多的点或行列的热图不适用,PPT会卡顿。
#https://mp.weixin.qq.com/s/p7LLLvzR5LPgHhuRGhYQBQ

拼图

可以在STHA网站找到现成的代码。

画图的思维:

1、我的数据适合什么图展示?

2、搜索画图代码

3、仿制示例数据

4、套代码,调整细节

玩转字符串

str_length()

length()#向量里面元素的个数

str_split()

str_sub(x,5,9)#提取5-9的元素

str_detect(x,"h")##是否含有关键词h,生成与X长度相等的逻辑值向量,可用于向量取子集;

str_detect(x,"h|s")##是否含有关键词h或者s,生成与X长度相等的逻辑值向量,可用于向量取子集;

str_starts(x,"h")##是否以h开头,生成与X长度相等的逻辑值向量,可用于向量取子集;

str_ends(x,"h")##是否以h结束,生成与X长度相等的逻辑值向量,可用于向量取子集;

str_replace(x,"o","a")#将x中的o替换为a,只替换出现的第一个o;

str_replace(x,"o|s","a")#将x中的o或者s替换为a,只替换出现的第一个o;

str_replace_all(x,"o","a")#将x中的o替换为a,替换所有的o;

str_remove(x," ")##将x中的第一个空格删除;

str_remove_all(x," ")##将x中的全部空格删除;

代码语言:text
复制
library(stringr)
str_split(x," ")##按照空格分隔
str_split(x," ",simplify=T)##列表简化为矩阵

玩转数据框

代码语言:text
复制
# arrange,数据框按照某一列排序
sort()##只排序某一列,其他列不改变;无法改变对应关系。
library(dplyr)
arrange(test, Sepal.Length) #将Sepal.LengthSepal.Length这一列从小到大排序
arrange(test, desc(Sepal.Length)) #从大到小

# distinct,数据框按照某一列去重复
distinct(test,Species,.keep_all = T)##将Species列去重复,保留所有列;

# mutate,数据框新增一列
mutate(test, new = Sepal.Length * Sepal.Width)
test$new= .....
##筛选行列
select()
filter()

# 连续的步骤
# 1.多次赋值,产生多个中间的变量
x1 = select(iris,-5)
x2 = as.matrix(x1)
x3 = head(x2,50)
pheatmap::pheatmap(x3)

# 2. 嵌套,代码不易读
pheatmap::pheatmap(head(as.matrix(select(iris,-5)),50))

# 3.管道符号传递,简洁明了
iris %>%
  select(-5) %>%
  as.matrix() %>%
  head(50) %>% 
  pheatmap::pheatmap()
##将管道符前面所有的结果传递给后面的函数,作为他的第一个参数
#用之前需要加载stringr包或dplyr包,快捷键ctrl+shift+M

条件或循环

代码语言:text
复制
rm(list = ls())

## 一.条件语句

###1.if(){ }

#### (1)只有if没有else,那么条件是FALSE时就什么都不做

i = -1
if (i<0) print('up')
if (i>0) print('up')

#理解下面代码
if(!require(tidyr)) install.packages('tidyr')

#### (2)有else
i =1
if (i>0){
  print('+')
} else {
  print("-")
}
i = 1
ifelse(i>0,"+","-")
ifelse(x,yes,no)
x:逻辑值或逻辑向量;
yes:逻辑值为TRUE时的返回值
no:逻辑值为FALSE时的返回值

x = rnorm(3)
x
ifelse(x>0,"+","-")

#ifelse()+str_detect(),王炸
samples = c("tumor1","tumor2","tumor3","normal1","normal2","normal3")
k1 = str_detect(samples,"tumor");k1
ifelse(k1,"tumor","normal")
k2 = str_detect(samples,"normal");k2
ifelse(k2,"normal","tumor")

#### (3)多个条件
i = 0
if (i>0){
  print('+')
} else if (i==0) {
  print('0')
} else if (i< 0){
  print('-')
}


library(dplyr)
i = 0
case_when(i>0 ~ "+",
          i<0 ~ "-",
          T ~ "0")
options(scipen = 20)
x = c(0.01,0.001,0.07,0.03,0.00001)
x
?ggpubr::stat_compare_means

case_when(x <= 0.0001~"****",
          x <= 0.001 ~"***",
          x <= 0.01 ~ "**",
          x <= 0.05 ~ "*",
          T ~"ns"
          )


ifelse(i>0,"+",ifelse(i<0,"-","0"))

## 二、for循环

for( i in 1:4){
  print(i)
}

#批量画图
par(mfrow = c(2,2))
for(i in 1:4){
  plot(iris[,i],col = iris[,5])
}
#批量装包
pks = c("tidyr","dplyr","stringr")
for(g in pks){
  if(!require(g,character.only = T))
    install.packages(g,ask = F,update = F)
}

# 隐式循环
apply(x, margin, fun, ...)
#x是数据框或者矩阵
#margin为行则是1,margin为列是2;
#fun为函数
#apply(test,2,mean)
#对test的每一列求平均值

sort(x)
#对x从小到大排序

head(x)
tail(x)
tail(x,1000)
#对x取前五或者后五;

identical(x1,x2)#判断x1和x2是否完全一致;

##举例
load(file="test2.Rdata")
a=apply(test,1,var)

x1=names(tail(sort(a),1000))

library(stringr)
x2=test %>%
  apply(1,var) %>%
  sort() %>%
  tail(1000) %>%
  names()
identical(x1,x2)

## 向量、列表的隐式循环——lappy
lappy(list,FUN, ...)
#对列表向量中的每个元素实施相同的操作
lappy(1:4,rnorm)

两个数据框的连接

代码语言:text
复制
#inner_join:取交集
#full_join:全连接
#left_join:左连接
#right_join:右链接

表达矩阵画箱线图——数据的格式转化

代码语言:text
复制
# 表达矩阵
set.seed(10086)#生成随机数,随机种子为10086
exp = matrix(rnorm(18),ncol = 6)
exp = round(exp,2)##保留两位小数;round(exp)为取整;
rownames(exp) = paste0("gene",1:3)
colnames(exp) = paste0("test",1:6)
exp[,1:3] = exp[,1:3]+1
exp

library(tidyr)
library(tibble)
library(dplyr)
dat = t(exp) %>% 
  as.data.frame() %>% 
  rownames_to_column() %>% 
  mutate(group = rep(c("control","treat"),each = 3))

pdat = dat%>% 
  pivot_longer(cols = starts_with("gene"),###cols=2:4
               names_to = "gene",##合并为一列,列名为gene
               values_to = "count")##合并为一列,列名为count
###pivot_longer宽变长
library(ggplot2)
p = ggplot(pdat,aes(gene,count))+
  geom_boxplot(aes(fill = group))+
  theme_bw()
p
p + facet_wrap(~gene,scales = "free")

一些函数

代码语言:text
复制
# 1.match-----
load("matchtest.Rdata")
x
y
## 如何把y的列名正确替换为x里面的ID?

## (1)分步解法
a = colnames(y)
b = x$file_name
k = match(a,b);k
#match(a,b)的意思是a里的每个元素在b的第几个位置上。
#是b的下标,可以给b取子集,也可以给与b对应的其他向量取子集。
colnames(y) = x$ID[k]

## (2)一步解法
load("matchtest.Rdata")
colnames(y) = x$ID[match(colnames(y),x$file_name)]

## (3)放弃match的解法
load("matchtest.Rdata")
rownames(x) = x$file_name
x = x[colnames(y),]
colnames(y) = x$ID

# 2.一些搞文件的函数----
dir() # 列出工作目录下的文件
dir(pattern = ".R$") #列出工作目录下以.R结尾的文件

file.create("douhua.txt") #用代码创建文件
file.exists("douhua.txt") #某文件在工作目录下是否存在
file.remove("douhua.txt") #用代码删除文件
file.exists("douhua.txt") #删掉了就不存在啦

## 可以批量的新建和删除
f = paste0("douhua",1:100,".txt")
file.create(f)
file.remove(f)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 常用可视化R包和函数
  • 绘图
  • 基础包
  • ggplot2
  • 作业
  • ggpubr
  • 图片保存
  • 拼图
  • 玩转字符串
  • 玩转数据框
  • 条件或循环
  • 两个数据框的连接
  • 表达矩阵画箱线图——数据的格式转化
  • 一些函数
相关产品与服务
图数据库 KonisGraph
图数据库 KonisGraph(TencentDB for KonisGraph)是一种云端图数据库服务,基于腾讯在海量图数据上的实践经验,提供一站式海量图数据存储、管理、实时查询、计算、可视化分析能力;KonisGraph 支持属性图模型和 TinkerPop Gremlin 查询语言,能够帮助用户快速完成对图数据的建模、查询和可视化分析。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档