如何在X轴上创建带有多个标签的图,以前的代码建议似乎不起作用

时间:2019-04-11 08:01:58

标签: r ggplot2 r-grid gtable

我有一些数据可以测量具有三个不同变量(暴露,季节和地点)的物种的驱除速率。我想创建一个图,其中X轴列出了Season和暴露,并且在图例中创建了站点。我已经在Excel中很容易地完成了此操作,并想在R中复制相同的类型。目前,我正在使用一段代码,该代码似乎对另一个有类似问题的用户都有效,但这似乎并没有和我一起工作?

脚本:

dput(Data2)
structure(list(Season = structure(c(2L, 2L, 2L, 3L, 3L, 3L, 1L, 
1L, 1L, 4L, 4L, 4L, 2L, 2L, 2L, 3L, 3L, 3L, 1L, 1L, 1L, 4L, 4L, 
4L), .Label = c("Autumn", "Spring", "Summer ", "Winter"), class = "factor"), 
Exposure = structure(c(1L, 3L, 2L, 4L, 3L, 2L, 4L, 3L, 2L, 
4L, 3L, 2L, 1L, 3L, 2L, 4L, 3L, 2L, 4L, 3L, 2L, 4L, 3L, 2L
), .Label = c(" Sheltered", "Exposed", "Moderately Exposed", 
"Sheltered"), class = "factor"), Average = c(1L, 2L, 4L, 
3L, 4L, 2L, 2L, 4L, 2L, 4L, 3L, 2L, 2L, 5L, 4L, 3L, 2L, 1L, 
1L, 1L, 2L, 4L, 2L, 2L), Site = c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L), SEM = c(0.5, 0.1, 0.4, 0.5, 1, 0.5, 0.5, 0.5, 
0.5, 0.5, 0.2, 0.5, 0.5, 0.1, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 
0.3, 0.2, 0.5, 0.5)), class = "data.frame", row.names = c(NA, 
-24L))


`setwd("C:/Users/phl5/Documents/PippaPhD")
 getwd()
 read.csv("Graphed_Data.csv")
 Data2<-read.csv("Graphed_Data.csv")

 library(ggplot2)
 library(gtable)
 library(grid)

 dodge<- position_dodge(width=0.9)

 ggplot(Data2, aes(x = interaction(Exposure, Season), y = Average, fill 
  = factor(Site))) +
 geom_bar(stat = "identity", position = position_dodge()) +
 geom_errorbar(aes(ymax = Average + SEM, ymin = Average - SEM), position 
 = dodge, width = 0.2)


 g1<- ggplot(data = Data2, aes(x = interaction(Exposure, Season), y = 
 Average, fill = factor(Site))) +
 geom_bar(stat = "identity", position = position_dodge()) +
 geom_errorbar(aes(ymax = Average + SEM, ymin = Average - SEM), position 
 = dodge, width = 0.2) +
 coord_cartesian(ylim = c(0, 12.5))+ 
 annotate("text", x = 1:12, y = 400,
       label = rep(c("Exposed", "Moderately Exposed", "Sheltered"),4)) +
 annotate("text", c(0.5, 1.5, 2.0, 2.5), y = -800, label = c("Spring", 
 "Summer", "Autumn", "Winter"))+
 theme_classic()+
 theme(plot.margin = unit(c(1,1,1,1), "lines"),
    axis.title.x = element_blank(),
    axis.text.x = element_blank())

 g2 <- ggplot_gtable(ggplot_build(g1))
 g2$layout$clip[g2$layout$name == "panel"] <- "off"
 grid.draw(g2)`

谁能看到我的代码中是否存在明显的问题,或者我可以使用其他脚本吗?

代码: Output get from current code, with the problem of no x axis codes appearing at all

This is the kind of output I would want, and that I can create in Excel

我是R的初学者,但是任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

由于您没有提供示例数据以与代码一起使用,因此我试图找出您在预先存在数据(cars)时遇到的问题。 查看所需的输出后,我在r中创建了一个barplot:

library(ggplot2)
ggplot(data = cars, aes(x =  speed, y = dist)) + 
  geom_bar(stat="identity", position = "dodge") 

enter image description here

您的代码存在手动覆盖x轴为空白的问题,如下所示:

ggplot(data = cars, aes(x =  speed, y = dist)) + 
  geom_bar(stat="identity", show.legend = F, position = "dodge") + 
  theme(
        axis.title.x = element_blank(),
        axis.text.x = element_blank())

如您所见,当您控制axis.title / axis.text

时,x轴及其标签消失了。

enter image description here

答案 1 :(得分:0)

编辑2:

关于OP在评论中的第二个问题:

  1. 无需添加geom_hline()来显示轴,只需将axis.line添加到theme()panel.spacing.x=unit(0, "lines")使其在各个面上连续即可。
gg <- ggplot(aes(x=as.factor(Site), y=Average, fill=as.factor(Site)), data=data)
gg <- gg + geom_bar(stat = 'identity')
gg <- gg + scale_fill_discrete(guide_legend(title = 'Site')) # just to get 'site' instead of 'as.factor(Site)' as legend title
# gg <- gg + scale_fill_manual(values=c('black', 'grey85'), guide_legend(title = 'Site')) # to get bars in black and grey instead of ggplot's default colors
# gg <- gg + theme_classic() # get white background and black axis.line for x- and y-axis
gg <- gg + geom_errorbar(aes(ymin=Average-SEM, ymax=Average+SEM), width=.3)
gg <- gg + facet_wrap(~Season*Exposure, strip.position=c('bottom'), nrow=1, drop=F)
gg <- gg + scale_y_continuous(expand = expand_scale(mult = c(0, .05))) # remove space below zero
gg <- gg + theme(axis.text.x = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.title.x = element_blank(),
                 axis.line = element_line(color='black'),
                 strip.placement = 'outside', # place x-axis above (factor-label-) strips
                 panel.spacing.x=unit(0, "lines"), # remove space between facets (for continuous x-axis)
                 panel.grid.major.x = element_blank(), # remove vertical grid lines
                 # panel.grid = element_blank(), # remove all grid lines
                 # panel.background = element_rect(fill='white'), # choose background color for plot area
                 strip.background = element_rect(fill='white', color='white')  # choose background for factor labels, color just matters for theme_classic()
)
  1. 要将曝光标签放置在小平面条中的季节标签上方,您可以更改每个条上覆盖的gtable
# facet factor levels
season.levels <- levels(data$Season)
exposure.levels <- levels(data$Exposure)

# convert to gtable
g <- ggplotGrob(gg)

# find the grobs of the strips in the original plot
grob.numbers <- grep("strip-b", g$layout$name)
# filter strips from layout 
b.strips <- gtable_filter(g, "strip-b", trim = FALSE)
# b.strips$layout shows the strips position in the cell grid of the plot
# b.strips$layout
season.left.panels <- seq(1, by=length(levels(data$Exposure)), length.out = length(season.levels))
season.right.panels <- seq(length(exposure.levels), by=length(exposure.levels), length.out = length(season.levels))
left <- b.strips$layout$l[season.left.panels]
right <- b.strips$layout$r[season.right.panels]
top <- b.strips$layout$t[1]
bottom <- b.strips$layout$b[1]

# create empty matrix as basis to overly new gtable on the strip
mat   <- matrix(vector("list", length = 10), nrow = 2)
mat[] <- list(zeroGrob())

# add new gtable matrix above each strip
for (i in 1:length(season.levels)) {
  res <- gtable_matrix("season.strip", mat, unit(c(1, 0, 1, 0, 1), "null"), unit(c(1, 1), "null"))
  season.left <- season.left.panels[i]
  # place season labels below exposure labels in row 2 of the overlayed gtable for strips
  res <- gtable_add_grob(res, g$grobs[[grob.numbers[season.left]]]$grobs[[1]], 2, 1, 2, 5)
  # move exposure labels to row 1 of the overlayed gtable for strips
  for (j in 0:2) {
    exposure.x <- season.left+j
    res$grobs[[c(1, 5, 9)[j+1]]] <- g$grobs[[grob.numbers[exposure.x]]]$grobs[[2]]
  }
  new.grob.name <- paste0(levels(data$Season)[i], '-strip')
  g <- gtable_add_grob(g, res, t = top,  l = left[i],  b = top,  r = right[i], name = c(new.grob.name))
  new.grob.no <- grep(new.grob.name, g$layout$name)[1]
  g$grobs[[new.grob.no]]$grobs[[nrow(g$grobs[[new.grob.no]]$layout)]]$children[[2]]$children[[1]]$gp <- gpar(fontface='bold')
}

grid.newpage()
grid.draw(g)

结果如下所示: enter image description here

  1. 要像您在示例图片中一样获得黑色和灰色的条形,请像这样更改ggplot:
gg <- ggplot(aes(x=as.factor(Site), y=Average, fill=as.factor(Site)), data=data)
gg <- gg + geom_bar(stat = 'identity')
# gg <- gg + scale_fill_discrete(guide_legend(title = 'Site')) # just to get 'site' instead of 'as.factor(Site)' as legend title
gg <- gg + scale_fill_manual(values=c('black', 'grey85'), guide_legend(title = 'Site')) # to get bars in black and grey instead of ggplot's default colors
gg <- gg + theme_classic() # get white background and black axis.line for x- and y-axis
gg <- gg + geom_errorbar(aes(ymin=Average-SEM, ymax=Average+SEM), width=.3)
gg <- gg + facet_wrap(~Season*Exposure, strip.position=c('bottom'), nrow=1, drop=F)
gg <- gg + scale_y_continuous(expand = expand_scale(mult = c(0, .05))) # remove space below zero
gg <- gg + theme(axis.text.x = element_blank(),
                 axis.ticks.x = element_blank(),
                 axis.title.x = element_blank(),
                 axis.line = element_line(color='black'),
                 strip.placement = 'outside', # place x-axis above (factor-label-) strips
                 panel.spacing.x=unit(0, "lines"), # remove space between facets (for continuous x-axis)
                 panel.grid.major.x = element_blank(), # remove vertical grid lines
                 # panel.grid = element_blank(), # remove all grid lines
                 # panel.background = element_rect(fill='white'), # choose background color for plot area
                 strip.background = element_rect(fill='white', color='white')  # choose background for factor labels, color just matters for theme_classic()
)

结果应如下所示: enter image description here 编辑:

对于OP在评论中的问题:

  1. 可以使用ggplot的{​​{1}}删除网格线:
theme()
  1. 每个季节只拥有一个标签会比较棘手。您需要编辑gg <- ggplot(aes(x=as.factor(Site), y=Average, fill=as.factor(Site)), data=data) gg <- gg + geom_bar(stat = 'identity') gg <- gg + geom_errorbar(aes(ymin=Average-SEM, ymax=Average+SEM), width=.3) gg <- gg + facet_wrap(~Season*Exposure, strip.position=c('bottom'), nrow=1, drop=F) gg <- gg + scale_fill_discrete(guide_legend(title = 'Site')) gg <- gg + theme(axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.x = element_blank(), panel.grid.major.x = element_blank(), # remove vertical grid lines # panel.grid = element_blank(), # remove al grid lines # panel.background = element_rect(fill='white'), # choose background color for plot area strip.background = element_rect(fill='white') # choose background for factor labels ) 中的gtable。 这样做的一种方法是:
ggplot

enter image description here

原始答案

我认为使用# facet factor levels season.levels <- levels(data$Season) exposure.levels <- levels(data$Exposure) # convert to gtable g <- ggplotGrob(gg) # find the grobs of the strips in the original plot grob.numbers <- grep("strip-b", g$layout$name) # filter strips from layout b.strips <- gtable_filter(g, "strip-b", trim = FALSE) # b.strips$layout shows the strips position in the cell grid of the plot b.strips$layout season.left.panels <- seq(1, by=length(levels(data$Exposure)), length.out = length(season.levels)) season.right.panels <- seq(length(exposure.levels), by=length(exposure.levels), length.out = length(season.levels)) left <- b.strips$layout$l[season.left.panels] right <- b.strips$layout$r[season.right.panels] top <- b.strips$layout$t[1] bottom <- b.strips$layout$b[1] # create empty matrix as basis to overly new gtable on the strip mat <- matrix(vector("list", length = 10), nrow = 2) mat[] <- list(zeroGrob()) # add new gtable matrix above each strip for (i in 1:length(season.levels)) { res <- gtable_matrix("season.strip", mat, unit(c(1, 0, 1, 0, 1), "null"), unit(c(1, 1), "null")) res <- gtable_add_grob(res, g$grobs[[grob.numbers[season.left.panels[i]]]]$grobs[[1]], 1, 1, 1, 5) new.grob.name <- paste0(levels(data$Season)[i], '-strip') g <- gtable_add_grob(g, res, t = top, l = left[i], b = top, r = right[i], name = c(new.grob.name)) new.grob.no <- grep(new.grob.name, g$layout$name) g$grobs[[new.grob.no]]$grobs[[nrow(g$grobs[[new.grob.no]]$layout)]]$children[[2]]$children[[1]]$gp <- gpar(fontface='bold') } grid.newpage() grid.draw(g) 可以最好地使用多面实现。

ggplot()

enter image description here