1

I need a plot with more than two variables, for that, I change my data frame with melt and I used ggplot2. I would like to put the label at the end of each line, I used ggrapel but instead of that I get a lot of labels, I appreciate any help.

Here the code:

obs1 <- melt(obs, id.vars = "Profundidad")

ggplot(obs1, aes(Profundidad, value, col = variable)) +
  geom_line() +
  geom_point(alpha = 0.5)+
  scale_color_manual(values = dath) +
  theme_linedraw() +
  theme(axis.text = element_text(size = 12),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    legend.position = "none")+
  labs(x =" Profundidad de secuenciación", y = "ASVs observados")+
  geom_label_repel(aes(label = variable),
    nudge_x = 0.1, 
    na.rm = FALSE)

And I get this:

plot result

Thank you very much.

pseudospin
  • 2,737
  • 1
  • 4
  • 19
geomicrobio
  • 321
  • 1
  • 3
  • 15

1 Answers1

3

Here is an example that should clarify how you can put the label at the end of each line.

library(ggplot2)
library(ggrepel)
library(dplyr)

# Create a dataset similar to your obs1
n <- 10
obs1 <- data.frame(Profundidad=rep(seq(0, 20000, length.out=n), n),
                   value = rep(sqrt(0:9),n)*rep(1:10, each=n),
                   variable=factor(rep(1:10, each=n)))

# Find the x and y position of the last point for each line
xy_labs <- obs1 %>%
           group_by(variable) %>%
           summarize(pos = which.max(Profundidad),
                     x = Profundidad[pos],
                     y = value[pos])

ggplot(obs1, aes(Profundidad, value, group=variable, col = variable)) +
  geom_line() +
  geom_point(alpha = 0.5)+
  theme_linedraw() +
  theme(axis.text = element_text(size = 12),
    axis.title.x = element_text(size = 16),
    axis.title.y = element_text(size = 16),
    legend.position = "none") +
  labs(x =" Profundidad de secuenciación", y = "ASVs observados")+
  geom_label_repel(data=xy_labs, aes(x=x, y=y, label = y), 
    nudge_x = 0.1, inherit.aes=F, 
    na.rm = FALSE)

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58