Home > Enterprise >  Nested ggplot histograms instead of cumulative
Nested ggplot histograms instead of cumulative

Time:10-10

using this table :

  Groups variable value
1     G1     VAR1  75.0
2     G1     VAR2  37.5
3     G2     VAR1  50.0
4     G2     VAR2  12.5

and this code :

color_list <- c("VAR1"="blue","VAR2"="red")

tab %>%
  mutate(Groups = fct_reorder(Groups, value)) %>%
  ggplot( aes(x=value, y=Groups,fill=factor(variable, levels = c("VAR1","VAR2")),label=Groups))   
  scale_fill_manual(values = color_list[unique(tab$variable)], guide = guide_legend(order = 1))    theme_minimal()

I managed to get the following figure: enter image description here

But here is what I expect :

enter image description here

As you can see it is rather a nested histogram I need instead of a cumulative histogram representation.

Does anyone have an idea how to do it using ggplot2?

Here is the table data in dput format if it can helps:

structure(list(Groups = c("G1", "G1", "G2", "G2"), variable = c("VAR1", 
"VAR2", "VAR1", "VAR2"), value = c(75, 37.5, 50, 12.5)), class = "data.frame", row.names = c(NA, 
-4L))

CodePudding user response:

You can try something like this, mixing up your code, the hints given by dario and something else:

library(ggplot2)
library(dplyr)
library(forcats)

color_list <- c("VAR1"="blue","VAR2"="red")

tab %>%
  mutate(Groups = fct_reorder(Groups, value)) %>%
  ggplot( aes(x = Groups, y = value, 
              fill  = factor(variable, levels = c("VAR1","VAR2")), 
              group = variable, 
              label = value))  
  # here you overlap your bars
  geom_bar (stat="identity", position = position_dodge(width = 0))  
  # here custom colors
  scale_fill_manual(values = color_list[unique(tab$variable)], 
                    guide  = guide_legend(order = 1))  
  # y (x) axis as you've pointed out, values and 30 by 30 labels, you can 
  # customize it of course
  scale_y_continuous("value", labels =c(seq(from = 0, to = 90, by = 30),tab$value), breaks = c(seq(from = 0, to = 90, by = 30),tab$value))    
  # some frills
  theme_minimal()  
  coord_flip()  
  labs(fill = "title")

enter image description here

  • Related