3
I’m making a chart similar to this one in the example, where I position the labels by group: I’m using the code:
set.seed(1000)
ano=factor(rep(1996:2016,2))
cod=c(rep("K1",21),rep("O1.3",21))
valor=round(c(cumsum(rnorm(21)),cumsum(cumsum(rnorm(21)))),1)
dat=data.frame(cod,ano,valor)
ggplot(dat,aes(x=ano,y=valor, group=cod, color=cod, label=valor)) +
geom_line(aes(linetype = cod), size=0.5) +
geom_point(aes(shape=cod), size=2.5) +
geom_text(data=subset(dat,cod=="K1"), aes(y = valor + 2), size=3) +
geom_text(data=subset(dat,cod=="O1.3"), aes(y = valor - 2), size=3) +
scale_colour_manual(values = c("red", "darkblue")) +
theme_minimal() +
theme(legend.position = "bottom",
legend.title = element_blank(),
axis.title.x = element_blank(),
axis.text.y = element_blank(),
axis.title.y = element_blank())
The result I would like is for the position of the labels to accompany the respective points, that is, when the blue line is above the red line, the corresponding blue labels are close to the respective points, above them, and vice versa. The same for the red line. Can anyone help me?
Excellent solution. I noticed that using a value greater than 1 in "dat$pos <- c(ifelse(dat[dat$Cod=="K1", 3] > dat[dat$Cod=="O1.3", 3], 1, -1), ifelse(dat[dat$Cod="O1.3", 3] > dat[dat$Cod=="K1", 3], 1, -1)"I receive the following warning: "Warning message: In if (params$y != 0) { : the condition has length > 1 and only the first element will be used". Any suggestions?
– EGazzoli
dat$pos <- c(ifelse(dat[dat$cod=="K1", 3] > dat[dat$cod=="O1.3", 3], 3, -3),
 ifelse(dat[dat$cod=="O1.3", 3] > dat[dat$cod=="K1", 3], 3, -3))
works perfectly for me.– Guilherme Parreira