Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a lollipop chart to compare groups

I have the following data frame

library(ggplot2)

set.seed(149)

x <- data.frame(
  region = factor(rep(1:10, each = 2)),
  group = rep(c("O", "E"), 10),
  mean = sample(1:2, 20, replace = TRUE)
)

x

   region group mean
1       1     O    2
2       1     E    1
3       2     O    1
4       2     E    2
5       3     O    1
6       3     E    1
7       4     O    1
8       4     E    1
9       5     O    1
10      5     E    2
11      6     O    2
12      6     E    2
13      7     O    1
14      7     E    1
15      8     O    1
16      8     E    1
17      9     O    1
18      9     E    2
19     10     O    1
20     10     E    1

I'm trying to create a lollipop chart, so I can make simple comparisons between each region (either 'O' or 'E'). I'd make a dumbbell plot, but a lot of the region's two groups are identical so the dumbbell plot ends up looking a lot like a dot plot.

Here's what I have so far...

ggplot(x, aes(y = region, x = mean, label = mean, fill = group, colour = group)) +
  geom_segment(aes(x = 0, y = region, xend = mean, yend = region), color = "grey50", size = 0.75) +
  geom_point(size = 3) +
  geom_text(nudge_x = 1.5, angle = -45)

enter image description here

Basically, for each region I'd like to plot two lines, one for group 'O' and one for group 'E.'

like image 714
afleishman Avatar asked Dec 15 '22 00:12

afleishman


1 Answers

We can accomplish this by using geom_linerange (the "stick"), geom_point (the "candy"), and by specifying position = position_dodge:

ggplot(x)+
    geom_linerange(aes(x = region, ymin = 0, ymax = mean, colour = group), 
                   position = position_dodge(width = 1))+
    geom_point(aes(x = region, y = mean, colour = group),
               position = position_dodge(width = 1))+
    coord_flip()

enter image description here

like image 155
bouncyball Avatar answered Jan 04 '23 06:01

bouncyball