Home > other >  Bar graph without overlap in linetype
Bar graph without overlap in linetype

Time:05-31

I am trying to make a bar graph with two categorical variables, one of which is a "superset" of the other. I would like to display the smaller one with colors, and the larger one with linetypes.

My problem is that I want the linetype to appear once per big category, not once per color. For example, in the graph below, I would like the solid line to go appear once (around the red and green surfaces together, without cutting them apart) and the dotted line to appear once (around the blue and purple surfaces together).

I would very much appreciate any help !

enter image description here

Below is code to reproduce the attached figure

library(tibble)
library(ggplot2)

set.seed(1234)

data <- runif(100)
cat_1 <- 1 * (data < 1/4)   2 * (data >= 1/4 & data < 1/2)  
  3 * (data >= 1/2 & data < 3/4)   4 * (data > 3/4)
cat_2 <- (cat_1 <= 2) * 1

df <- tibble(x = data,
             cat_1 = factor(cat_1),
             cat_2 = factor(cat_2))

ggplot(df, aes(x = "", fill = cat_1, linetype = cat_2, color = cat_2))  
  geom_bar()  
  scale_x_discrete(drop = FALSE)  
  scale_linetype_manual(values = c("dotted", "solid"))  
  scale_color_manual(values = c("black", "black"))

CodePudding user response:

You'll need to relevel cat2 so that it is in the same order as its subsets in cat1, then you can use the group aesthetic with a second geom_bar with its alpha set to 0

df <- tibble(x = data,
             cat_1 = factor(cat_1),
             cat_2 = factor(cat_2, c(1, 0)))

ggplot(df, aes(x = "", fill = cat_1))  
  geom_bar()  
  geom_bar(alpha = 0, aes(linetype = cat_2, group = cat_2), 
           color = "black", size = 1.5)  
  scale_x_discrete(drop = FALSE)  
  scale_linetype_manual(values = c("solid", "dotted"))  
  scale_color_manual(values = c("black", "black"))  
  theme_light(base_size = 16)  
  guides(fill = guide_legend(override.aes = list(colour = NA)))  
  theme(legend.key.size = unit(10, 'mm'))

enter image description here

  • Related