一、绘图基本概念
- 相关R包:作图(ggplot2),拼图(patchwork),导出(eoffice)
- 基础包绘图函数(区分高级和低级):
高级绘图函数:plot(); hist();boxplot()....
低级绘图函数:lines();curve(); text() - 基础包绘图参数:用于函数内部,没有设定时则为默认值。
font=字体;lty=线类型 - 最终出图
plot(iris[,1],iris[,3],col = iris[,5])
text(6.5,4, labels = 'hello')
二、ggplot基本概念
加载
if(!require(ggplot2))install.packages('ggplot2')
library(ggplot2)
1. ggplot入门模板:
ggplot(data = test)+
geom_point(mapping = aes(x = Sepal.Length,
y = Petal.Length,
color = Species))
2. 映射:领导思维,自动分配颜色
3. 手动设置形状
ggplot(data = y)+
geom_point(mapping = aes(x = displ,
y = hwy),shape=15)
4.分面
ggplot(data = test) +
geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) +
facet_wrap(~ Species)
双分面
#增加一列group
test$Group = sample(letters[1:5],150,replace = T)
ggplot(data = test) +
geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) +
facet_grid(Group ~ Species)
5.几何对象
叠加局部映射
ggplot(data = test) +
geom_smooth(mapping = aes(x = Sepal.Length,
y = Petal.Length))+
geom_point
(mapping = aes(x = Sepal.Length, y = Petal.
全局映射:
更简洁的代码(画图一模一样):因为GEOM管的是图层,ggplot是负责全局,mapping放在ggplot括号里,意味着后面所有都要听这个
ggplot(data = test,mapping = aes(x = Sepal.Length, y = Petal.Length))+
geom_smooth()+
geom_point()
6. 练习
#练习6-2
# 1.尝试写出下图的代码
# 数据是iris
# X轴是Species
# y轴是Sepal.Width
# 图是箱线图
# 2. 尝试在此图上叠加点图,
# 能发现什么问题?
ggplot(data = iris) +
geom_boxplot(mapping = aes(x = Species, y = Sepal.Width,color=Species))+
geom_point(mapping = aes(x = Species,y = Sepal.Width))
# 3.用下列代码作图,观察结果
ggplot(test,aes(x = Sepal.Length,y = Petal.Length,color = Species)) +
geom_point()+
geom_smooth(color = "black")
小技巧:可以用iris$自动补齐
网友评论