So I want to annotate outside my plot to create a new x-axis, as is shown here by Henrik: Multi-row x-axis labels in ggplot line chart
But everything breaks when I try to add a log y axis.
Here's my example data:
# 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))
Here's my code showing what I want the x axis to look like, but without a log y axis:
# 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)
This is all fine, but as soon as I toss in
scale_y_log10()
To yield:
# 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)
it all stops working and I get errors:
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).
(You actually get more errors, but they're just repeats for each annotation you add)
Can anyone offer some suggestions?