Home > Blockchain >  ggplot2 Plotting scatterplot with 2 variables and labelling x-axis based on another variable
ggplot2 Plotting scatterplot with 2 variables and labelling x-axis based on another variable

Time:04-02

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.

CodePudding user response:

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())

CodePudding user response:

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

CodePudding user response:

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

  • Related