ggplot第八篇 图片主题和格式修改

作者: 小洁忘了怎么分身 | 来源:发表于2018-08-30 16:37 被阅读21次
微信公众号生信星球同步更新我的文章

1.示例数据

在公众号回复:dexp.csv,获得示例数据。
示例数据和学习内容来自基因课。
读取数据:

dexp <- read.csv("dexp.csv",row.names = 1)#设置第一列为行名

示例数据:40个基因,每个基因9个重复,加上这9个重复各自的观测值,以及每个基因的长度。

2.作图

library(ggplot2)
p<-ggplot(data = dexp, aes(x = Gene, y = Expression)) 
pp <-p+geom_point(aes(color = Sample))

3.主题设置

(1)局部设置-单次操作一张图

part <- pp + theme_bw()

(2)全局设置-操作后面所有的图

theme_set(theme_bw())

4.主题的选择

适合做科研的:theme_bw
9个内置主题的对比
(这里使用了scales的labs参数来设置图片标题)

theme_gray<- pp + theme_gray() +
  labs(title = "gray")

theme_grey <- pp + theme_grey() +
  labs(title = "grey")

theme_bw <- pp + theme_bw() +
  labs(title = "bw")

theme_classic <- pp + theme_classic() +
  labs(title = "classic")

theme_dark <- pp + theme_dark() +
  labs(title = "dark")

theme_light <- pp + theme_light() +
  labs(title = "light")

theme_linedraw <- pp + theme_linedraw() +
  labs(title = "linedraw")

theme_minimal <- pp + theme_minimal() +
  labs(title = "minimal")

theme_void <- pp + theme_void() +
  labs(title = "void")

grid.arrange(theme_gray,theme_grey,theme_bw,theme_classic,theme_dark,theme_light,theme_linedraw,theme_minimal,theme_void)
9种主题的对比

这里内置的主题风格多样,接下来介绍如何自己给主题动刀。

5.私人定制

还是以图片pp为例,介绍可以动刀的地方:

(1)标题(名称)-title

标题内容用scales修改,这里主要讲格式的变化

  • 图片标题plot.title
  • 坐标轴标题(名称)axis.title
    上文生成的pp是没有标题的,用标度设置的简单方法加上标题。
bioinfoplanet <- pp + labs(title = "bioinfoplanet")
默认左对齐

设置水平对齐方式用hjust参数,0表示左对齐,0.5居中,1右对齐。顺便把字号调大,设置斜体的代码一起写出。

bioinfoplanet <- bioinfoplanet +
  theme(plot.title = element_text(size = 20, hjust = 0.5,face="italic"))

需要修改坐标轴名称(标题)的话,将代码中的plot.title改为axis.title,axis.title.x,axis.title.y。

bioinfoplanet <- bioinfoplanet+
 theme(axis.title=element_text(face="italic"))

总结一下:能修改的文本格式有:

  • 水平对齐方式 hjust 0 0.5 1分别表示左对齐/右对齐/居中
  • 垂直对齐方式 vjust 0 0.5 1分别表示上对齐/下对齐/居中
  • 字号 size
  • 倾斜 face ="italic"
    这里的h和v是horizontal和vertical的意思。
    之前的教程图种有的x轴坐标密集,出现倾轧重叠,解决办法是设置x轴坐标的倾斜角度,并设置上下居中。👇
bioinfoplanet <- bioinfoplanet+
  theme(axis.title.x=element_text(face="italic"),
        axis.text.x = element_text(angle=50,vjust = 0.5))

(2)图例的位置

bioinfoplanet <- bioinfoplanet+
   theme(legend.position = c(0.95,0.75), #设置水平和垂直位置
         legend.background = element_rect(fill="white"))

注意:这个调整位置是把图例加入到了图片上,不是和默认的一样并列在图片右边了。

ps:我的搞笑日常

刚才设置了一下背景为白色,没有看到变化,手贱改成红色,于是尴尬了

bioinfoplanet <- bioinfoplanet+
  theme(plot.background = element_rect(fill="red"))
做出了shi一样的图

放弃治疗啦,其实我想改那个灰色的背景。。。还是直接设置theme_bw好了。

相关文章

网友评论

    本文标题:ggplot第八篇 图片主题和格式修改

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