美文网首页科研绘图
2024-04-09 | ggplot各种图展示

2024-04-09 | ggplot各种图展示

作者: 千万别加香菜 | 来源:发表于2024-04-08 09:41 被阅读0次

最近在学习R,在这里介绍下ggplot绘制的各种图形及代码,还是非常好用的

1 数据

用的数据是R中自带的mpg数据集,长这样(部分)

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)
4 结果展示
plot.png

相关文章

网友评论

    本文标题:2024-04-09 | ggplot各种图展示

    本文链接:https://www.haomeiwen.com/subject/jrztxjtx.html