Home > database >  Using ggrepel to add two labels for geom_point in ggplot
Using ggrepel to add two labels for geom_point in ggplot

Time:01-11

I would like to label geom_points using two columns of information.

As an example, in the below, I would like the points to labelled:

A, ($5m)
B, $2m
C, ($3m)
D, $3m

Using geom_text_repel I am only able to add the first part of the label, but not quite sure how to add the y-value into the label as above.

alpha <- c("A","B","C","D")
percent <- c(0.012, -0.02, 0.015, -0.01)
flow <- c(-5, 2, -3, 3)
to <- c(0.1, 0.15, 0.2, 0.1)

df <- data.frame(alpha,percent,flow,to)

df %>%
  ggplot(aes(x = percent, y = flow, label = alpha))   
  geom_point(aes(size = to))   
  geom_text_repel(show.legend = FALSE, size = 3)  
  scale_size_continuous(labels = scales::percent)   
  theme_bw()   
  scale_x_continuous(labels = scales::percent_format(accuracy = 0.1L))   
  scale_y_continuous(labels = scales::dollar_format(negative_parens = TRUE, suffix = "m"))  

Chart output with one label

CodePudding user response:

You can preformat the y label (using a similar method) and paste it in.

df$ylbl <- paste(df$alpha, scales::dollar_format(negative_parens = TRUE, suffix = "m")(df$flow))
df %>%
  ggplot(aes(x = percent, y = flow, label = alpha))   
  geom_point(aes(size = to))   
  geom_text_repel(aes(label = ylbl), show.legend = FALSE, size = 3)  
  scale_size_continuous(labels = scales::percent)   
  theme_bw()   
  scale_x_continuous(labels = scales::percent_format(accuracy = 0.1L))   
  scale_y_continuous(labels = scales::dollar_format(negative_parens = TRUE, suffix = "m"))  
# Warning: integer literal 0.1L contains decimal; using numeric value

enter image description here

  •  Tags:  
  • Related