0

I have the following dataframe:

df<-data.frame(ID = c(1,2,3,4,5,6,7,8,9,10),
         group = c(1,1,1,1,1,2,2,2,3,3),
         level = c(0.1,0.5,0.2,0.3,0.6,0.7,0.8,0.5,0.9,0.3))

I would like to use ggplot2 to plot a scatter plot, where every point (x,y) corresponds to the values of (ID,level). But I want to label the x-axis based on the group value, so that the x-axis in this case would have 3 ticks: under tick "1", there would be 5 points, tick "2" with 3 points and tick "3" with 2 points.

3
  • 2
    Could you please add the current and expected output and what has already failed? Commented Apr 1, 2022 at 19:22
  • From your description e.g "under tick "1", there would be 5 points" it sounds that your result could be achieved by simply mapping group directly on x. Maybe you could clarify how your plot should look like. Commented Apr 1, 2022 at 19:24
  • Sorry what I meant was I want the plot to look like three different scatterplots (stitched together), one based on each group value and the points based on (ID, level) values, so for example under tick "1", the points that are plotted should be: (1, 0.1), (2, 0.5), (3, 0.2), (4, 0.3), (5, 0.6). Commented Apr 1, 2022 at 19:46

3 Answers 3

1

Similar idea as by Allan but with some additional tweaking to show the group labels as tick labels:

library(ggplot2)

breaks <- tapply(df$ID, df$group, median)
ggplot(df, aes(ID, level)) +
  geom_point() +
  scale_x_continuous(breaks = breaks, labels = NULL) +
  facet_grid(~group, scales = "free_x", switch = "x" , space = "free_x") +
  theme(strip.placement = "outside",
        strip.background.x = element_blank())

Sign up to request clarification or add additional context in comments.

Comments

1

Are you looking for facets?

ggplot(df, aes(ID, level)) + 
  geom_point() + 
  facet_grid(.~group, scales = "free_x", space = "free_x") +
  scale_x_continuous(breaks = 1:10, expand = expansion(0, 0.5)) +
  theme(panel.spacing = unit(0, "mm"),
        text = element_text(size = 16),
        strip.background = element_rect(fill = "#A0B6FF", color = "black"),
        panel.border = element_rect(colour = "grey", fill = NA),
        strip.text = element_text(size = 20))

enter image description here

1 Comment

This time your faster than. Spend to much time on tweaking the plot. ;)
0

The tidyverse way:

library(tidyverse)
df %>% ggplot(aes(x = group, y = level)) + 
  geom_point(aes(color = as.factor(ID)), size = 2) +
  scale_x_continuous(breaks = seq(1:3))

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.