Facet wrap of a lollipop diagram

139 views Asked by At

I'm building on a previous question that got answered, but now I am struggling to apply this to my problem. I have the following data:

cluster <- c("Joe", "Sam", "Bob")
var1 <- c(22.9, 0, 0)
var2 <- c(57.8, 0, -25.1)
var3 <- c(45.9, -25.5, 63.9)

data <- as.data.frame(
  cbind (cluster, var1, var2, var3)
)

I'd like to make a facet wrap of a lollipop diagram where there are three lollipop diagrams like on this page, where each facet is Joe, Sam, and Bob; the variable names var1, var2, and var3 are on the left hand side, and each lollipop is a segment connecting the value for each key-value pair (Joe-var3 = 45.9) to zero in the center.

Picture shows the example that I'm trying to adapt. enter image description here

2

There are 2 answers

0
Snot On

I think following code full-fills most of your requirement. You may adjust detailed settings (color, background.....)

library(tibble)
library(tidyr)
library(ggplot2)


data1<-
    tibble(
        cluster=c("Joe", "Sam", "Bob"),
        var1=c(22.9, 0, 0),
        var2=c(57.8, 0, -25.1),
        var3=c(45.9, -25.5, 63.9)
    ) %>% 
    pivot_longer(
        cols=c("var1","var2","var3"),
        names_to="varname",
        values_to="varvalue"
    )


ggplot(data1) +
    geom_col(aes(y=varname,x=varvalue),fill='seagreen')+
    coord_cartesian(xlim=c(-100,100))+
    facet_wrap(~ cluster)
0
UseR10085 On

The problem is cbind will convert everything into character variable.

cluster <- c("Joe", "Sam", "Bob")
var1 <- c(22.9, 0, 0)
var2 <- c(57.8, 0, -25.1)
var3 <- c(45.9, -25.5, 63.9)

data <- as.data.frame(
  cbind (cluster, var1, var2, var3)
)

str(data)

#>'data.frame': 3 obs. of  4 variables:
#> $ cluster: chr  "Joe" "Sam" "Bob"
#> $ var1   : chr  "22.9" "0" "0"
#> $ var2   : chr  "57.8" "0" "-25.1"
#> $ var3   : chr  "45.9" "-25.5" "63.9"

See all are converted into chr. Better to use cbind.data.frame like

library(tidyverse)

data <- cbind.data.frame(cluster, var1, var2, var3)

str(data)

#>'data.frame': 3 obs. of  4 variables:
#> $ cluster: chr  "Joe" "Sam" "Bob"
#> $ var1   : num  22.9 0 0
#> $ var2   : num  57.8 0 -25.1
#> $ var3   : num  45.9 -25.5 63.9

Now see that cbind.data.frame has conserved the data type i.e. character as character (chr) and numeric as numeric (num). Now for plotting, you can use

data %>% 
  pivot_longer(cols = -cluster, values_to = 'mark') %>% 
  ggplot( aes(x=name , y=mark)) +
  geom_bar(stat="identity", fill="#69b3a2", width=0.6) +
  coord_flip() +
  #theme_ipsum() +
  theme(
    panel.grid.minor.y = element_blank(),
    panel.grid.major.y = element_blank()
  ) +
  ylab("mark") +
  xlab("") +
  facet_wrap(~cluster)

enter image description here