Home > Software design >  How to plot a grouped geom_bar plot having a dataframe?
How to plot a grouped geom_bar plot having a dataframe?

Time:09-22

I have a dataframe like this one:

enter image description here

and want to plot in R something like this:

enter image description here

But for some reason I am really struggling with the grouped geom_bar code... Can you help me please?

CodePudding user response:

We may use barplot from base R

barplot(t(df1), beside = TRUE, col = c("blue", "orange", "grey", 
       "yellow", "lightblue" ))

-output

enter image description here


Or if we need a ggplot/plotly

library(ggplot2)
library(dplyr)
library(tidyr)
library(plotly)
library(tibble)
p <- df1 %>% 
   rownames_to_column('rn') %>%
   pivot_longer(cols = -rn) %>%
   ggplot(aes(x = rn, y = value, fill = name))  
        geom_col(position = 'dodge')   
     theme_bw()
ggplotly(p)

-output

enter image description here

data

df1 <- structure(list(A = c(65, 9, 7, 70, 9), B = c(23, 4, 5, 53, 2), 
    C = c(42, 5, 2, 17, 7), D = c(51, 7, 5, 57, 5), E = c(14, 
    2, 2, 13, 4)), class = "data.frame", row.names = c("AAA", 
"BBB", "CCC", "DDD", "EEE"))

CodePudding user response:

Here's a solution using the tidyverse package that contains ggplot2 and tidyr packages. Additionally, this answer includes plotting the numbers as text on top of the bars.

library(tidyverse)

df1 %>%
  # Convert rownames to a new column named rowname
  rownames_to_column() %>%
  # Put data into long format
  pivot_longer(cols = -rowname,
               names_to = "letter") %>%
  # Build plot
  ggplot(aes(x = rowname, y = value, fill = letter))  
  # Draw column plot and set position = "dodge" so every column
  # starts from 0 value
  geom_col(position = "dodge", width = 0.9)  
  # Add text, sum 2 to value so the label is plotted on top of the column
  geom_text(aes(y = value 2, label = value), 
            position = position_dodge(width = 0.9))  
  # Add bw theme or any other
  theme_bw()

column plot

  • Related