ggplot2主题的一些可能会用到的操作

时间:2022-07-24
本文章向大家介绍ggplot2主题的一些可能会用到的操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
首先是构建数据集
df <- data.frame(x = 1:10, y = (1:10)^2) 
最基本的散点图
ggplot(df, aes(x = x, y = y)) + 
  geom_point()

image.png

去掉灰色背景

参考 Remove elements from ggplot

ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank())

image.png

添加坐标轴的竖线

https://ggplot2.tidyverse.org/reference/theme.html

ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank(),
        axis.line.y = element_line(color="red",size=5))

image.png

在右边再加一个坐标轴

参考 https://ggplot2.tidyverse.org/reference/sec_axis.html

这个链接还有如何操作第二个坐标轴的一些其他例子

ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank(),
        axis.line.y = element_line(color="red",size=5))+
  scale_y_continuous(sec.axis = dup_axis())

image.png

去掉坐标轴上的文字(text)
ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank(),
        axis.line.y = element_line(color="red",size=5),
        axis.text.x = element_blank())+
  scale_y_continuous(sec.axis = dup_axis())

image.png

去掉坐标轴上的小短线(ticks)
ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank(),
        axis.line.y = element_line(color="red",size=5),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank())+
  scale_y_continuous(sec.axis = dup_axis())

image.png

去掉坐标轴标题 (title)
ggplot(df, aes(x = x, y = y)) + 
  geom_point()+
  theme(panel.background = element_blank(),
        axis.line.y = element_line(color="red",size=5),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.title.x = element_blank())+
  scale_y_continuous(sec.axis = dup_axis())

image.png