Write R code to create a bar plot for the categories Fruit <- c("Apple", "Banana", "Cherry") with the values Quantity <- c(10, 15, 7). Use base R barplot() to create a bar chart with green bars and the title "Fruit Quantities"
Bar plots are used to compare categorical data or discrete values. In R, you can create bar plots using the base barplot()
function or ggplot2
.
# Sample data
categories <- c("A", "B", "C", "D")
values <- c(5, 8, 2, 6)
# Create a bar plot
barplot(values, names.arg = categories, main = "Basic Bar Plot", col = "blue")
library(ggplot2)
df <- data.frame(category = categories, value = values)
ggplot(df, aes(x = category, y = value)) +
geom_bar(stat = "identity", fill = "red") +
ggtitle("Bar Plot with ggplot2") +
theme_minimal()
Bar plots are ideal for comparing quantities across different groups or categories.