0

I want to draw a stacked or grouped bar plot saying against each individual what is valid/real_valid and Invalid. I tried so many things googling but could not conclude that.

My real data look like:

name                   valid real_valid Invalid
Parvathi, Sowmya g     59         10       9
Joshi, Srikanth r      34         10      15
Satyanaik, Shivaru     32         16       4
Kumar, Rajesh          28          6      16
Shrigiri, Girish s     27         21       1
  Vasandani, Dhanu     13          3       8

And here is some code to create the table:

name <- c("Parvathi", "Joshi", "Satyanaik", "Kumar", "Girish", "Vasandani")
valid  <- c(59, 34, 32, 28, 27, 13)
real_valid <- c(10, 10, 16, 6, 21, 3)
Invalid  <- c(9, 15, 4, 16, 1, 8)

df <- data.frame(name, valid, real_valid, Invalid)
zabop
  • 6,750
  • 3
  • 39
  • 84

2 Answers2

0

First create a data frame:

name <- c("Parvathi", "Joshi", "Satyanaik", "Kumar", "Girish", "Vasandani")
valid  <- c(59, 34, 32, 28, 27, 13)
real_valid <- c(10, 10, 16, 6, 21, 3)
Invalid  <- c(9, 15, 4, 16, 1, 8)

df <- data.frame(name, valid, real_valid, Invalid)

Then pivot data and plot:

install.packages("tidyverse") #if you don't have it installed yet
library(tidyverse) #load tidyverse, which is needed for the below to work

df %>%
  pivot_longer(2:4, names_to = "Variable", values_to = "Value") %>% 
  ggplot(aes(x=name, y=Value, fill=Variable))+
  geom_col()

Result:

enter image description here

Is this what you needed?

johnjohn
  • 716
  • 2
  • 9
  • 17
0

Same result using base R plot.

  name <- c("Parvathi", "Joshi", "Satyanaik", "Kumar", "Girish", "Vasandani")
  valid  <- c(59, 34, 32, 28, 27, 13)
  real_valid <- c(10, 10, 16, 6, 21, 3)
  Invalid  <- c(9, 15, 4, 16, 1, 8)
  
  df <- data.frame(name, valid, real_valid, Invalid)

  dfmat = as.matrix(df[,2:4])  # barplot() needs a matrix
  rownames(dfmat) = df$name  # needed for correct display
  dfmat = t(dfmat)

  barplot(dfmat, legend = rownames(dfmat), beside = TRUE)  # use beside = False if you want the stacked version
 

enter image description here

Paul
  • 2,850
  • 1
  • 12
  • 37