create a side-by-side bar plot in r in r

To create a side-by-side bar plot in R using ggplot2, you can use the position_dodge() function to create a dodge position adjustment of the objects being stacked. Here's an example code:

main.r
library(ggplot2)
# create sample data
df <- data.frame(
  group = rep(c("A", "B"), each = 3),
  category = c("X", "Y", "Z", "X", "Y", "Z"),
  value = c(1, 2, 3, 2, 4, 6)
)

# create bar plot
ggplot(df, aes(x = category, y = value, fill = group)) +
   geom_col(position = position_dodge(width = 0.9), width = 0.8, alpha = 0.8) +
   theme_classic()
347 chars
13 lines

In this example, the geom_col() function is used to create the bar plot with position = position_dodge(width = 0.9) to adjust the position of the bars so they are side-by-side. width is the amount of space between the bars (0.9 is the default), and alpha controls the opacity of the bars (0-1).

The theme_classic() function is used to apply a classic ggplot2 theme to the plot.

related categories

gistlibby LogSnag