Day5: ggplot2绘图
基础包绘图函数
plot(iris[,1],iris[,3],col = iris[,5])
text(6.5,4, labels = 'hello')
1. ggplot2入门绘图模版
ggplot(data = <DATA>)+
<GEOM_FUNCTION>(mapping = aes<MAPPINFGS>)
ggplot(data = iris)+
geom_point(mapping = aes(x = Sepal.Length,
y = Petal.Length))
ggplot2的特殊语法 :列名不带引号,函数之间写加号

2. 属性设置,size点的大小,alpha透明度,点的形状
ggplot(data = iris)+
geom_point(mapping = aes(x = Sepal.Length,y = Petal.Length),
size = 5,
alpha = 0.5,
shape = 8)

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

2.2 统一设置
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,
color = Species))+
scale_color_manual(values = c("blue","grey","red"))

使用配色R包自定义映射颜色,需要提前加载paletteer包
library(paletteer)
ggplot(data = iris)+
geom_point(mapping = aes(x = Sepal.Length,
y = Petal.Length,
color = Species))+
scale_color_paletteer_d("awtools::mpalette")

paletteer集成多个配色R包
palettes_d_names可查看包的内容
空心形状和实心形状都用color设置颜色
只有既有边框又有实心的,才需要color和fill两个参数
一个geom函数画出来的所有东西称之为一个几何对象
几何对象叠加
#局部设置和全局设置
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()
局部设置仅对当前图层有效
全局设置对所有图层有效

使用全局设置逐层画图:
ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))

ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_boxplot()

ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_boxplot()+
geom_point()

ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_boxplot()+
geom_point()+
geom_jitter()

ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_boxplot()+
geom_point()+
geom_jitter()+
theme_bw() #设置主题背景

使用R包patchwork对多张图片进行拼图
library(ggplot2)
library(patchwork)
a = ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_smooth()+
geom_boxplot()+
geom_point()+
geom_jitter()+
theme_bw()
b = ggplot(data = iris,mapping = aes(x = Species, y = Petal.Length,color = Species))+
geom_smooth()+
geom_boxplot()+
theme_bw()
a+b
图片保存,关闭画板
ggsave("iris.png")
ggsave(p,filename = "iris.png")
dev.off
将图片导出为ppt格式
library(eoffice)
topptx(p,"iris.pptx")
代码可运行但是不出图:画板可能被占用,多次运行dev.off() 到null device为止
绘图代码网站:STHDA - Accueil
从生信技能树数据挖掘班搬运

1102

被折叠的 条评论
为什么被折叠?



