2023년 1월 21일 토요일

a few more examples of creating a basic bar chart in R

 here are a few more examples of creating a basic bar chart in R using different data and options:

  1. Using the ggplot2 package to create a stacked bar chart with different fill colors for each group of data:Copy code
# Load the ggplot2 package 
library(ggplot2) 
 # Create stacked bar chart with different fill colors for each group of data 
ggplot(mtcars, aes(x = factor(gear), fill = factor(cyl))) + geom_bar(position = "fill") + xlab("Number of Gears") + ylab("Frequency") + ggtitle("Stacked Bar Chart of Gear Frequencies by Number of Cylinders")
  1. Using the barplot() function with a matrix input to create a grouped bar chart:Copy code
# Create a matrix of frequencies 
gear_cyl_table <- table(mtcars$gear, mtcars$cyl
# Create a grouped bar chart 
barplot(gear_cyl_table, beside = TRUE, xlab = "Number of Gears", ylab = "Frequency", main = "Grouped Bar Chart of Gear Frequencies by Number of Cylinders")
  1. Using the barplot() function with a data frame input and ggplot2 to create a stacked bar chart with error bars:Copy code
# Load the ggplot2 package 
library(ggplot2) 
# Create a data frame for the bar chart 
gear_cyl_df <- data.frame(gear = rep(c("3", "4", "5"), each = 3), cyl = rep(c("4", "6", "8"), 3), freq = c(15, 7, 2, 4, 4, 0, 2, 1, 2)) 
# Create a stacked bar chart with error bars 
ggplot(gear_cyl_df, aes(x = gear, y = freq, fill = cyl)) + geom_bar(stat = "identity") + geom_errorbar(aes(ymin = freq - sd, ymax = freq + sd), width = 0.2) + xlab("Number of Gears") + ylab("Frequency") + ggtitle("Stacked Bar Chart of Gear Frequencies by Number of Cylinders with Error Bars")


댓글 없음:

댓글 쓰기