make a ggplot bar figure with 2 categorical variables and date on the x axis in r

You can create a bar plot in ggplot2 with two categorical variables on the y-axis and dates on the x-axis using the following code snippet:

library(ggplot2)

# Sample data
data <- data.frame(Category1 = c("A", "B", "A", "B"),
                   Category2 = c("X", "Y", "X", "Y"),
                   Date = as.Date(c("2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04")),
                   Value = c(5, 7, 3, 9))

# Create the ggplot bar plot
ggplot(data, aes(x = Date, y = Value, fill = Category2)) +
  geom_bar(stat = "identity", position = "dodge") +
  facet_wrap(~Category1, scales = "free_y") +
  labs(title = "Bar Plot with Two Categorical Variables", x = "Date", y = "Value")
546 chars
14 lines

In this code, replace the sample data with your own dataset where Category1 and Category2 are your two categorical variables, Date is your date variable, and Value is the value you want to plot in the bar chart. The facet_wrap function allows you to separate the bars by Category1.

Make sure to install and load the ggplot2 library before running the above code:

install.packages("ggplot2")
library(ggplot2)
45 chars
3 lines

related categories

gistlibby LogSnag