Home > Net >  How to increase the gap interval for dumbbell plot using ggplot in R
How to increase the gap interval for dumbbell plot using ggplot in R

Time:10-22

Desired

I wanted to obtain this graph, however, when I plotted my graph I got a graph where the names on y-axis were "squished". When I used the following code:

lower = c(83, 81, 80, 71, 69, 63, 63, 62, 54)
upper = c(112, 96, 111, 141, 125, 89, 178, 107, 130)
loc = c("YISHUN", "WOODLANDS", "HOUGANG", "ANG MO KIO"  "TAMPINES", "SENGKANG", "GEYLANG", "BEDOK", "JURONG WEST")
df = data.frame(lower, upper, loc)
ggplot(df)  
 geom_point(aes(lower, loc), color = "Blue")   
 geom_point(aes(upper, loc), color = "Red")  
 geom_segment(aes(x = lower, y = loc, xend = upper, yend = loc))

The graph I got: (*Note that I did not include the entire dataset, so some of those appearing in my graph will not be present in the dataset) What I got

How do I space out the loc for each y-axis so that they do not overlap? Also I realise that it was ordered by the alphabetical order of loc. Is there any way I can order it based on the ordering of lower instead?

CodePudding user response:

First, you can increase size of the plot or make text's size smaller.

Second, order group base on lower can be done like code below.

df1.order <- df1 %>%
  dplyr::arrange(desc(lower)) %>%
  mutate(loc = factor(loc))

df1 %>%
  mutate(loc = factor(loc, levels = df1.order$loc, ordered = TRUE)) %>%
  ggplot()  
  geom_point(aes(lower, loc), color = "Blue")   
  geom_point(aes(upper, loc), color = "Red")  
  geom_segment(aes(x = lower, y = loc, xend = upper, yend = loc))  
  theme(axis.text = element_text(size = 5))

enter image description here

  • Related