zl程序教程

您现在的位置是:首页 >  其他

当前栏目

R语言-画图

2023-03-07 09:03:14 时间

1.ggplot入门级绘图模板

特殊语法:列名不加引号,行末带加号

2.属性设置

1.手动设置

2.映射:按照数据框的某一列来定义图的某个属性

映射:根据数据的某一列的内容设置颜色

手动设置:把图形设置为一个或n个颜色,与数据内容无关

Q1-指定映射的具体颜色:

首先要有映射,并且根据映射的类型数给出颜色数。

颜色:英文单词;十六进制颜色代码

Q2-区分color和fill

Q2.1 空心形状和实心形状都用color设置颜色

Q2.2 既有边框又有内心,既有color又有fill

3.分面:根据数据的某一列把图分成若干张子图

用来分面的列:若干个并列的值,分类型的变量;分面的个数是有限的

双分面:

不要修改内置数据!

练习题

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

4.几何对象

5.统计变换

有y就必须加stat='identity'

用..prop..来与列名进行区分

练习题

library(ggpubr)
ggboxplot(iris,x = "Species",y = "Sepal.Width",fill = 'Species')+
  geom_point()
ggboxplot(iris,x = "Species",y = "Sepal.Width",fill = 'Species')+
  geom_jitter() #避免重叠

6.位置关系

7.坐标系

总结:完整的绘图模板

3.ggpubr

练习题

ggplot(data = iris,mapping = aes(x = Sepal.Width,
                                 y = Species))+
  geom_violin(mapping = aes(fill=Species))+
  geom_boxplot()+
  geom_jitter(mapping = aes(shape=Species)) #要有映射

4.图片的保存和导出

dev.off() #关闭画板,报错也没问题,如果多次运行也不出图就dev.new()

保存不同类型的图片文件:

pdf(file = "p.pdf",width =12,height = 9)
print(p)
dev.off()

png(filename = "p.png",width = 1200,height = 900,res = 300)
print(p)
dev.off()

ggplot

ggsave(p,filename = "p.pdf",width = 12,height = 9)
ggsave(p,filename = "p.png",width = 12,height = 9)