create a Dot Plot for multiple variables by group using ggplot

Viewed 516

I am attempting to produce a horizontal dot plot of group medians for multiple variables. For the dummy data below I would like to have a "line" for each variable( x,y,z,w) with the seven group medians plotted on each line and distinguished by color. Any help appreciated Thanks!

library(dplyr)
    dat=data.frame(x=runif(100,1,10),y=runif(100,1,5),z=runif(100,1,15),
    w=runif(100,1,20),grp=sample(LETTERS[1:7],100,replace=T))
    dat_summ=dat %>% group_by(grp)%>%
      summarise_all(funs(median(., na.rm = TRUE)))

Something like this

x|_______A_____B____C_D__EF_G
y|_______C_D_E_____F__________B____A_G
z|etc.
w|etc.
 |
 |
 |
 |
 |____________________________________________________________________
    |           |            |            |
    5           10           15           20
1 Answers

You can make lines using geom_segment (find max value per group to now where the end is and they all start from the same position (minimum)).

It's a little bit messy, but with real data should look better.

library(tidyverse)
data_Let <- gather(dat_summ, wxyz, value, x:w)
data_Seg <- summarise(group_by(data_Let, wxyz), MAX = max(value))

ggplot(data_Let) +
    geom_segment(aes(x = min(data_Let$value),  xend = MAX,
                     y = wxyz, yend = wxyz), data_Seg) +
    geom_point(aes(value, wxyz, color = grp)) +
    geom_text(aes(value, wxyz, label = grp), vjust = -0.5, size = 3) +
    scale_y_discrete(limits = rev(sort(unique(data_Let$wxyz)))) +
    labs(x = "Median")

enter image description here

Related