Home > OS >  How to label specific points on ggplot chart?
How to label specific points on ggplot chart?

Time:07-19

I have a data and I would like to plot a ggplot. I want to add labels for my points if the "Pro" column has a value of 10. How do I do that?

structure(list(Countries = c("Afghanistan", "Albania", "Algeria", 
"Angola", "Antigua and Barbuda"), a = c(5, 7.38126363692877, 
9.99376780626781, 5, 1.21609883215906), b = c(20155, 6491.65444434, 
NA, 40311, 42811), pro = c(10, NA, NA, 10, NA)), class = "data.frame", row.names = c(NA, 
-5L))

data %>% 
ggplot(aes(x = a, y = b,label=pro)) geom_point() 

CodePudding user response:

It's not clear what you want the labels to be, since you didn't include that in your question. Presumably you want the points labelled with the country name if pro equals 10. To do this you could use ifelse to create the vector of labels:

data %>% 
  ggplot(aes(x = a, y = b, label = ifelse(pro == 10, Countries, '')))  
  geom_point()  
  geom_text(hjust = 0, nudge_x = 0.1)

enter image description here

If you want the labels just to be the value of pro when pro equals 10, you could do

data %>% 
  ggplot(aes(x = a, y = b, label = ifelse(pro == 10, pro, '')))  
  geom_point()  
  geom_text(hjust = 0, nudge_x = 0.1)

enter image description here

  • Related