Open duttashi opened 6 years ago
Annotation is the art of adding text labels to a visualization. In this first example, I provide how to
Example 1
library(ggplot2)
set.seed(10)
df.rnorm <- data.frame(rnorm = rnorm(10000, mean = 5))
# Here we have a histogram with a dashed line at the mean. The mean is 5.
ggplot(data = df.rnorm, aes(x = rnorm)) +
geom_histogram(bins = 50) +
geom_vline(xintercept = 5, color = "red", linetype = "dashed")
ggplot(data = df.rnorm, aes(x = rnorm)) +
geom_histogram(bins = 50) +
geom_vline(xintercept = 5, color = "red", linetype = "dashed") +
annotate("text", label = "Mean = 5", x = 4.5, y = 170, color = "white")
This question was originally asked on SO
df1 <- data.frame(y=c(TRUE,TRUE,FALSE,TRUE,FALSE,TRUE,FALSE,FALSE,FALSE),
x=c(1,2,3,4,5,6,7,8,9))
df2 <- data.frame(y=c(1,1,0,1,0,1,0,0,0),
x=c(1,2,3,4,5,6,7,8,9))
# yplace <- mean(as.numeric(levels(as.factor(df$y))))
yplace1 <- 1.5
yplace2 <- 0.5
# Solution
getYplace <- function(Y) {
if (is.numeric(Y)) {
res <- mean(unique(Y))
} else {
res <- 1.5
}
return(res)
}
library(ggplot2)
ggplot(df1, aes(x, y)) +
geom_point() +
annotate("text", label = "read me", x = mean(df1$x), y = getYplace(df1$y))
ggplot(df2, aes(x, y)) +
geom_point() +
annotate("text", label = "read me", x = mean(df2$x), y = getYplace(df2$y))
that correspond to male and female ratings. There are 45 tiles, and my very cumbersome solution is to add 90 annotate layers. This question was originally asked on SO
Solution
library(ggplot2)
d <- expand.grid(x=1:5,y=1:5)
d$z <- rnorm(nrow(d))
d$f <- sample(LETTERS, size = nrow(d), replace = TRUE)
d$m <- sample(LETTERS, size = nrow(d), replace = TRUE)
dd <- tidyr::gather(d, gender, label, -x,-y,-z)
ggplot(dd, aes(x,y,fill=z)) + geom_tile() +
geom_text(aes(label=label,colour=gender, hjust = ifelse(gender=="f",0,1))) +
scale_colour_manual("gender", values=c("pink","green"))
How to add an annotation (a label) to a ggplot2 plot (using R) with a position relative to another element, namely, above a bar in a bar chart.
Solution
d <- data.frame(x = c("var1", "var2"), y = c(.2, 100))
library(ggplot2)
ggplot(d, aes(x = x, y = y)) +
geom_col() + geom_text(aes( label = "hi!"), vjust = -0.5)