ggplot2:注释外部图+ y对数比例

时间:2017-05-30 00:34:55

标签: r ggplot2

所以我想在我的情节之外注释创建一个新的x轴,如Henrik所示:Multi-row x-axis labels in ggplot line chart

但是当我尝试添加日志y轴时,一切都会中断。

这是我的示例数据:

# Data
Type = rep(c("type1", "type2"), each = 6)
Gen = rep(rep(c("-", "G+"), each = 3), 2)
A = c(4.98E+05, 5.09E+05, 1.03E+05, 3.08E+05, 5.07E+03, 4.22E+04, 6.52E+05, 2.51E+04, 8.66E+05, 8.10E+04, 6.50E+06, 1.64E+06)
B = c(6.76E+07, 3.25E+07, 1.11E+07, 2.34E+06, 4.10E+04, 1.20E+06, 7.50E+07, 1.65E+05, 9.52E+06, 5.92E+06, 3.11E+08, 1.93E+08)
df = melt(data.frame(Type, Gen, A, B))

这里的代码显示了我希望x轴看起来像什么,但没有log y轴:

# main graph without log y axis
g1 <- ggplot(data = df, aes(x = interaction(Type, Gen, lex.order = TRUE), y = value, group = 1)) +
    stat_summary(fun.y = "mean", geom = "bar") +
    scale_x_discrete(limits = c("type1.-", "type2.-", "type1.G+", "type2.G+")) +
    coord_cartesian(ylim = c(1, 10^9), expand = FALSE) +
    annotate(geom = "text", x = (1:4), y = -1*10^8, label = c("type1", "type2", "type1", "type2"), size = 4) +
    annotate(geom = "text", x = 3.5, y = -2*10^8, label = "G+", size = 4) +
    geom_segment(aes(x = 3, y = -1.5*10^8, xend = 4, yend = -1.5*10^8))+
    theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
          axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          panel.grid.major.x = element_blank(),
          panel.grid.minor.x = element_blank())

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

这一切都很好,但是一旦我进入

scale_y_log10()

屈服:

# main graph with log y axis
g1 <- ggplot(data = df, aes(x = interaction(Type, Gen, lex.order = TRUE), y = value, group = 1)) +
    scale_y_log10() +
    stat_summary(fun.y = "mean", geom = "bar") +
    scale_x_discrete(limits=c("type1.-", "type2.-", "type1.G+", "type2.G+")) +
    coord_cartesian(ylim = c(1, 10^9), expand = FALSE) +
    annotate(geom = "text", x = (1:4), y = -1*10^2, label = c("type1","type2","type1","type2"), size = 4) +
    annotate(geom = "text", x = 3.5, y = -2*10^2, label = "G+", size = 4) +
    geom_segment(aes(x = 3, y = -1.5*10^2, xend = 4, yend = -1.5*10^2)) +
    theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
          axis.title.x = element_blank(),
          axis.text.x = element_blank(),
          panel.grid.major.x = element_blank(),
          panel.grid.minor.x = element_blank())

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

它全部停止工作,我得到错误:

1: In self$trans$transform(x) : NaNs produced
2: Transformation introduced infinite values in continuous y-axis 
3: Removed 4 rows containing missing values (geom_text).

(实际上你会得到更多错误,但是他们只是为你添加的每个注释重复了一次)

有人可以提供一些建议吗?

0 个答案:

没有答案