Home > database >  How to plot two overlappling histograms like this?
How to plot two overlappling histograms like this?

Time:06-09

The data is

y0 y1
M 100 200
F 50 250

How to plot the histogram like this? Note that M and F do not block each other, so this is not the case in his

CodePudding user response:

First, convert your data to long format with pivot_longer().

library(ggplot2)
library(tidyr)

df_long <- pivot_longer(df, cols = c("y0","y1"))

ggplot(data = df_long)  
  geom_col(aes(x = name, y = value, fill = sex))  
  scale_fill_manual(values = c("M" = "blue", "F" = "darkorange"))  
  theme(legend.position = "bottom")
   

enter image description here data:

df <- data.frame(sex = c("M","F"),
           y0 = c(100,50),
           y1 = c(200,250))

CodePudding user response:

Here's a straight solution:

library(tidyverse)
my_df <- tribble(~ sex, ~ y0, ~ y1,
                 "M", 100, 200,
                 "F", 50, 250)
my_df %>% 
  pivot_longer(starts_with("y")) %>% 
  ggplot(aes(name, value, fill = sex))   
  geom_col(position = "stack")

CodePudding user response:

If your data is like df below:

library(tidyverse)

df <- tibble::tribble(
  ~V1,  ~y0,  ~y1,
  "M", 100L, 200L,
  "F",  50L, 250L
)

df %>% 
  pivot_longer(-V1) %>% 
  ggplot(aes(x = name, y = value, fill = V1))  
  geom_bar(stat = 'identity')

Which gives:

enter image description here

  • Related