Reputation: 8117
I have a ggplot plot with two labels. I want to add both labels onto my plot, aligned vertically. I want my second label drawn below the first label, but they should not overlap.
So if I want to draw the first label at (20,90), where should the second label go? Obviously, it depends on the y-axis of the data set and the height required for the first label.
Q: The coordinates are hard-coded (see my script) and won't work for a new data set. I want to come up with a way such that the two labels are always aligned vertically for any data set and scaling. My potential solutions are:
Line1\nLine2
tableGrob
from the gridExtra
package.I don't know how to make 1 works. In 2, I'm not sure how to make tableGrob
works with individual labels. What's the easiest solution?
library(ggplot2)
data <- data.frame(x=c(1:100), y=x+rnorm(100))
p <- ggplot(data=data, aes_string(x='data$x', y='data$y')) + geom_point()
str1 <- "italic(y) == \"1.7\" + \"1\" * italic(x) * \",\" ~ ~italic(r)^2 ~ \"=\" ~ \"0.91\""
str2 <- "italic(y) == \"9.7\" + \"1\" * italic(x) * \",\" ~ ~italic(r)^2 ~ \"=\" ~ \"9.91\""
above <- annotate("text",
label=str1,
x=20,
y=90,
parse=TRUE)
below <- annotate("text",
label=str2,
x=20,
y=83,
parse=TRUE)
p <- p + above
p <- p + below
print(p)
Upvotes: 1
Views: 576
Reputation: 36076
You could use atop
to make single label out of the two labels, stacked one atop the other:
str3 = 'atop(italic(y) == \"1.7\" + \"1\" * italic(x) * \",\" ~ ~italic(r)^2 ~ \"=\" ~ \"0.91\",
italic(y) == \"9.7\" + \"1\" * italic(x) * \",\" ~ ~italic(r)^2 ~ \"=\" ~ \"9.91\")'
p + annotate("text",
label=str3,
x=20,
y=90,
parse=TRUE)
You do still need to enter the coordinates for the single label.
Upvotes: 1
Reputation: 3230
Try the package cowplot
which gives you the function draw_label
which lets you add layers with relative positioning:
library(ggplot2)
library(cowplot)
data <- data.frame(x = 1:100, y = (1:100) + rnorm(100))
p <- ggplot(data = data,
aes(x = x,
y = y)) +
geom_point()
ggdraw(p) +
draw_label(expression(paste(italic(y) == 1.7 + 1 * italic(x),
", ",
italic(r)^2 == 0.91)),
.2, .9) +
draw_label(expression(paste(italic(y) == 9.7 + 1 * italic(x),
", ",
italic(r)^2 == 9.91)),
.2, .83)
Upvotes: 2
Reputation: 77096
You could try something like this,
library(gridExtra)
library(grid)
table_label <- function(label, params=list()) {
params <- modifyList(list(hjust=0, x=0), params)
mytheme <- ttheme_minimal(padding=unit(c(1, 1), "mm"),core = list(fg_params = params), parse=TRUE)
disect <- strsplit(label, "\\n")[[1]]
m <- as.matrix(disect)
tableGrob(m, theme=mytheme)
}
txt <- 'italic(y) == 1.7 + 1 * italic(x) * "," ~~italic(r)^2 ~ "=" ~ 0.91\n
italic(y) == 9.7 + 1 * italic(x) * "," ~~italic(r)^2 ~ "=" ~ 9.91'
library(ggplot2)
qplot(1:10,1:10) +
annotation_custom(table_label(txt), xmin=0, xmax=5, ymin=7.5)
Upvotes: 4