# Load necessary libraries
library(ggplot2)
# Create sample data
data <- data.frame(
Category = c("A", "B", "C", "D"),
Value1 = c(30, 50, 20, 40),
Value2 = c(15, 25, 10, 30)
)
# Reshape data for ggplot
data_long <- tidyr::gather(data, key = "Variable", value = "Value", -Category)
# Create a bar plot with ggplot
plot <- ggplot(data_long, aes(x = Category, y = Value, fill = Variable)) +
geom_bar(stat = "identity", position = "dodge", width = 0.7) +
# Customize the appearance
theme_minimal() +
labs(title = "Bar Plot with Legend",
x = "Categories",
y = "Values",
fill = "Variables") +
# Add a legend
scale_fill_manual(values = c("Value1" = "blue", "Value2" = "red")) +
# Position the legend
theme(legend.position = "top")
# Display the plot
print(plot)