Show y values for x axis breaks

Viewed 56

I want to highlight add y-value text to a plot, but only for those points where I set up x-axis breaks. In my original data, x values are discreate, but to keep things simple lets use a sequence from 0 to 125 as an example and I hope i can transfer the solution for my data on my own. If I simply put

... + geom_text(aes(label=y),size=3) + ...

it'll result in a mess that can't be read. E.g.

enter image description here

This is what my code for the plot and for my example data looks like.

data %>%
  group_by(x) %>%  
  summarise(y= sum(y,na.rm = TRUE)) %>% 
  ggplot( aes(x=x,y=y,group=1)) + 
  scale_x_continuous(breaks = c(1,50,75,100,125))+   
  geom_text(aes(label = y), size = 3)+
  geom_line()


# while the data after summarised looks somethat like this
x <- seq(1,125,1)
y <- x^2
data <- data.frame(cbind(x,y))

Thank you very much for all responses. Kind regards

EDIT: In my comments I referred to "strange behavior" and I just wanted to show you what happens on my real data.

strange things happen here

This does not happen when using the marked answer.

2 Answers

You can include the subset argument to the geom_text function, which allows you only to plot a subset of the values which satisfy a condition.

x <- seq(1,125,1)
y <- x^2

dat <- data.frame(cbind(x,y))

dat %>%
  group_by(x) %>%  
  summarise(y= sum(y,na.rm = TRUE)) %>% 
  ggplot( aes(x=x,y=y,group=1)) + 
  scale_x_continuous(breaks = c(1,50,75,100,125))+   
  geom_text(data = subset(dat, x %in% c(1,50,75,100,125)), aes(label = y), size = 3)+
  geom_line()

enter image description here

Instead of using a "second" dataframe for the labels you can add a column with the labels to your dataset. As I learned from Thomas Lin Pedersen's workshop on ggplot2 this approach is more general, e.g. in case you want to use geom_text_repel from the ggrepel package.

library(dplyr)
library(ggplot2)

x <- seq(1,125,1)
y <- x^2

dat <- data.frame(cbind(x,y))

dat %>%
  group_by(x) %>%  
  summarise(y= sum(y,na.rm = TRUE)) %>% 
  mutate(label = ifelse(x %in% c(1,50,75,100,125), y, "")) %>% 
  ggplot( aes(x=x,y=y,group=1)) + 
  scale_x_continuous(breaks = c(1,50,75,100,125))+   
  geom_text(aes(label = label), size = 3)+
  geom_line()

Created on 2020-04-04 by the reprex package (v0.3.0)

Related