Elliot
Elliot

Reputation: 57

labeling geom_point in ggplot R

I am trying to recreate a plot and I have several lines in there, which are in the legend but next to this the plot also has some points. How could I put labels in this plot at the points. Note that the points are not in the data frame. My code looks like this now:

ggplot(df, aes(x=tau_3)) + 
  geom_line(aes(y= a1, color = "blue")) + 
  geom_line(aes(y= a2, color = "green"))+ 
  xlim(0,0.6) + 
  ylim(0,0.4) +  
  geom_point(aes(0,0), size =5 , shape = "square")  + 
  geom_point(aes(0,1/6), size =5 , shape = "circle") +   
  geom_point(aes(0,0.1226), size =5 , shape = "triangle")  +  
  scale_color_discrete(name = "Legend", labels = c("GLO", "GEV"))

Upvotes: 3

Views: 6165

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

A way of solving the problem is to put the points' coordinates and shapes in an auxiliary data.frame df_points and use it in both geom_point and geom_text.

As for the lines, reshape the data from wide to long format and one call to geom_line will be enough. Set argument inherit.aes = FALSE and in the case of geom_point also set show.legend = FALSE.

library(ggplot2)
library(dplyr)
library(tidyr)

df_points <- data.frame(x = rep(0, 3), 
                        y = c(0, 1/6, 0.126),
                        shape = factor(c("square", "circle", "triangle"), 
                                       levels = c("square", "circle", "triangle")))

df %>%
  pivot_longer(
    cols = starts_with('a'),
    names_to = 'y',
    values_to = 'a'
  ) %>%
  ggplot(aes(tau_3, a, color = y)) +
  geom_line() +
  geom_point(data = df_points, 
             mapping = aes(x, y, shape = shape), 
             size = 5, 
             show.legend = FALSE,
             inherit.aes = FALSE) +
  geom_text(data = df_points, 
            mapping = aes(x, y, label = shape), 
            vjust = -1.5, hjust = 0,
            inherit.aes = FALSE) +
  xlim(0,0.6) + 
  ylim(0,0.4) +  
  scale_color_manual(name = "Legend", 
                     values = c("blue", "green"),
                     labels = c("GLO", "GEV")) +
  scale_shape_manual(values = c("square", "circle", "triangle"))

enter image description here

Test data

set.seed(2020)
n <- 20
tau_3 <- runif(n, 0, 0.6)
a1 <- runif(n, 0, 0.4)
a2 <- runif(n, 0, 0.4)
df <- data.frame(tau_3, a1, a2)

Upvotes: 1

stefan
stefan

Reputation: 123783

To label the points you can add geom_text layers with point coordinates and the label.

Using mtcars as example data set try this:

library(ggplot2)

ggplot() +
  geom_point(data = mtcars, aes(hp, mpg, color = factor(cyl))) +
  geom_point(aes(200, 25), color = "black") +
  geom_point(aes(100, 12), color = "purple") +
  geom_text(aes(200, 25), label = "I'm a black point", color = "black", nudge_y = .5) +
  geom_text(aes(100, 12), label = "I'm a purple point", color = "purple", nudge_y = -.5)

Upvotes: 2

Related Questions