1

I am wanting to plot changes in weight(X) per day(Y). I would like to label the very first datapoint, then every seventh.

I am currently using geom_point() + geom_label(aes(label = weight)). I was thinking maybe rep() would do this, but I can't figure out how; if it even will.

MJL
  • 161
  • 7
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 22 '21 at 03:06
  • 1
    By "the very first datapoint, then every seventh" do you mean 1, 7, 14... or 1, 8, 15... ? – neilfws Apr 22 '21 at 03:27
  • Check https://stackoverflow.com/questions/56994202/label-every-nth-element-in-ggplot-depending-on-row-column and https://stackoverflow.com/questions/45147849/how-to-show-every-second-r-ggplot2-x-axis-label-value – Ronak Shah Apr 22 '21 at 03:39
  • @neilfws, 1, 7, 14, etc. – MJL Apr 22 '21 at 07:02

2 Answers2

4

You can pass the data to geom_label and filter for row numbers that match your condition.

Assuming that by "every seventh" you mean 7, 14, 21... use %% 7 == 0. Otherwise use %% 7 == 1 for 8, 15, 22...

library(dplyr)
library(ggplot2)

mydata <- data.frame(x = 2 * (1:49), 
                     y = 3 * (1:49))

mydata %>% 
  ggplot(aes(x, y)) + 
  geom_point() + 
  geom_label(aes(label = x), 
             data = . %>% 
               filter(row_number() %% 7 == 0 | row_number() == 1))

Result:

enter image description here

neilfws
  • 32,751
  • 5
  • 50
  • 63
  • Thanks! This works perfectly. I used `filter(row_number() %% 7 == 1 | row_number() == 1))` and this got me what I needed: eg. the first Monday, then every consecutive Monday. – MJL Apr 22 '21 at 07:13
0
my_data = data.frame(timecount = 1:210,
                     value = 1:210 + 20*sin((1:30)/10))

library(dplyr); library(ggplot2)

my_data %>%
  ggplot(aes(timecount, value)) +
  geom_point()

enter image description here

my_data %>%
  mutate(row = row_number()) %>%
  filter(row %% 7 == 1) %>%   # modulo operator: only keep rows
                              # where the remainder of row / 7 is 1,
                              # i.e.  1, 8, 15, etc.
  ggplot(aes(timecount, value)) +
  geom_point()

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53