Home > Back-end >  Plot bar graph with 3 variables
Plot bar graph with 3 variables

Time:01-08

Im sure this is fairly easy but im new to R. how do you plot a bar graph with the following data.

D_data <- data.frame(month=c(1,2,3,4),
                 A=c(22,55,66,88),
                 B=c(7,8,5,8),
                 c=c(1,2,9,10))

The bar graph as x axis as the month, y as the value of each category A, B, C. There should be 3 bars for each month.

CodePudding user response:

Since you tagged this with ggplot2, I assume you don't want a base R solution, but you can use pivot_longer() to tidy your data and then use ggplot() with another argument.

More importantly, you don't have enough values to make boxplots with month and letters. However, you can make a bar plot.

library(tidyverse)
D_data %>%
  pivot_longer(cols = -month) %>%
  ggplot(aes(x = name, y = value, fill = name))  
  geom_boxplot()

enter image description here

D_data %>%
  pivot_longer(cols = -month) %>%
  ggplot(aes(x = month, y = value))  
  geom_bar(stat = "identity", 
           position = "dodge",
           aes(fill = name))

enter image description here

  • Related