最近在學(xué)習(xí)R狸相,在這里介紹下ggplot
繪制的各種圖形及代碼,還是非常好用的
1 數(shù)據(jù)
用的數(shù)據(jù)是R中自帶的mpg
數(shù)據(jù)集皇帮,長這樣(部分)
manufacturer | model | displ | year | cyl | trans | drv | cty | hwy | fl | class |
---|---|---|---|---|---|---|---|---|---|---|
audi | a4 | 1.8 | 1999 | 4 | auto(l5) | f | 18 | 29 | p | compact |
audi | a4 | 1.8 | 1999 | 4 | manual(m5) | f | 21 | 29 | p | compact |
audi | a4 | 2.0 | 2008 | 4 | manual(m6) | f | 20 | 31 | p | compact |
audi | a4 | 2.0 | 2008 | 4 | auto(av) | f | 21 | 30 | p | compact |
audi | a4 | 2.8 | 1999 | 6 | auto(l5) | f | 16 | 26 | p | compact |
audi | a4 | 2.8 | 1999 | 6 | manual(m5) | f | 18 | 26 | p | compact |
2 加載包
# install.packages(c("sf", "cowplot", "patchwork", "gghighlight", "ggforce", "ggfx"))
library(tidyverse)
library(gghighlight)
library(cowplot)
library(patchwork)
library(ggforce)
library(ggridges)
3 繪圖
p1 <- ggplot(mpg, aes(x = cty, y = hwy))+
geom_point()+
geom_smooth()+
labs(title = "1: geom_point() + geom_smooth()")+
theme(plot.title = element_text(face = "bold"))
p2 <- ggplot(mpg, aes(x = cty, y = hwy))+
geom_bin_2d()+
labs(title = "2: geom_bin_2d()")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p3 <- ggplot(mpg, aes(x = drv, fill = drv))+
geom_bar()+
labs(title = "3: geom_bar()")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p4 <- ggplot(mpg, aes(x = cty))+
geom_histogram(binwidth = 2, color = "white")+
labs(title = "4: geom_histogram()")+
theme(plot.title = element_text(face = "bold"))
p5 <- ggplot(mpg, aes(x = cty, y = drv, fill = drv))+
geom_violin()+
labs(title = "5: geom_violin()")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p6 <- ggplot(mpg, aes(x = cty, y = drv, fill = drv))+
geom_boxplot()+
labs(title = "6: geom_boxplot()")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p7 <- ggplot(mpg, aes(x = cty, fill = drv))+
geom_density(alpha = 0.7)+
labs(title = "7: geom_density")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p8 <- ggplot(mpg, aes(x = cty, y = drv, fill = drv))+
geom_density_ridges()+
labs(title = "8: geom_density_ridges")+
guides(fill = FALSE)+
theme(plot.title = element_text(face = "bold"))
p9 <- ggplot(mpg, aes(x = cty, y = hwy))+
geom_density_2d()+
labs(title = "9: geom_density_2d()")+
theme(plot.title = element_text(face = "bold"))
p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9
ggsave("plot.png", width = 15, height = 10, dpi = 600)