R:多表ggplot/X轴色/segment

2021-06-25  本文已影响0人  胡童远

表1:做箱图

df = read.table("phylum_abundance.txt", header=T, sep="\t", row.names=1)
df$Phylum = rownames(df)
## boxplot
# BGI cohort
input = melt(df, id='Phylum')
input$Phylum = factor(input$Phylum, levels = unique(input$Phylum))

表2:做柱形图

# CGR2
cgr = read.table("phylum_abundace_cgr2.txt", header=T, sep="\t")
cgr$Phylum = factor(cgr$Phylum, levels = unique(cgr$Phylum))

X轴配色

# X color
col_text = c(rep("indianred3", 7), rep("deepskyblue3", 11))

segment和配色

# segment data
seg = data.frame(Phylum = cgr$Phylum, no = c(1:18))
seg$x_start = seg$no - 0.5
seg$x_end = seg$no + 0.5
col_set = col_text
names(col_set) <- seg$Phylum
seg$Phylum = factor(seg$Phylum, levels = unique(seg$Phylum))

ggplot boxplot barplot segment

ggplot(NULL, aes(x, y)) + 
  theme_classic() +
  geom_boxplot(input, mapping=aes(x=Phylum, y=value*100),
               color = "deepskyblue3", 
               position = position_nudge(x = -0.2), 
               width = 0.3, 
               outlier.color = NA, 
               lwd = 1) +
  geom_point(input, mapping=aes(x=Phylum, y=value*100),
             pch = 19, color = "deepskyblue3", 
             size = 0.2,
             position = position_nudge(x = -0.2)) +
  geom_bar(cgr, mapping=aes(x=Phylum, y=num*100),
           stat="identity", width = 0.3, 
           color = "indianred3", 
           fill = "white", lwd = 1,
           position = position_nudge(x = 0.2)) +
  labs(x="", y="Relative abundance (%)") +
  theme(panel.grid = element_line(colour = 'white')) +
  theme(axis.title = element_text(size = 18),
        axis.text = element_text(size = 10),
        axis.line = element_line(size = 1),
        axis.ticks = element_line(size = 1)) +
  theme(axis.text.x = element_text(angle = 60, hjust = 1, 
                                   color = col_text)) +
  scale_y_continuous(limits=c(0, 100), expand = c(0, 0)) +
  geom_segment(seg, mapping=aes(
      x = x_start, 
      y = 100, 
      xend = x_end,
      yend = 100,
      color = Phylum), size = 2) +
  scale_color_manual(values = col_set) +
  theme(legend.position = "none")

ggsave(p, filename="merge2.pdf", width = 12)
ggsave(p, filename="merge.png", width = 8)
上一篇下一篇

猜你喜欢

热点阅读