Creating a Simple Bar Chart in R Using GGPlot: A Step-by-Step Guide
Code
# Import necessary libraries
library(ggplot2)
# Create data frame from given output
data <- read.table("output.txt", header = TRUE, sep = "\\s+")
# Convert predictor column to factor for ggplot
data$Hair <- factor(data$Hair)
# Create plot of estimated effects on length
ggplot(data, aes(x = Hair, y = Estimate)) +
geom_bar(stat = "identity") +
labs(x = "Hair Colour", y = "Estimated Effect on Length")
Explanation
This code is used to create a simple bar chart showing the estimated effects of different hair colours on length.
- The
read.tablefunction reads in the output from the R console and stores it in a data frame. - The
factorfunction converts theHaircolumn into a factor, allowing us to easily identify each category (e.g., brown, red, blond). - The
ggplotfunction is used to create a bar chart of the estimated effects on length for each hair colour.
Notes
- This code assumes that the output from the R console has been saved in a file called “output.txt”.
- The
sep = "\\s+"argument inread.tablespecifies how to separate values in the text file. - The
labsfunction is used to add labels to the plot, and thestat = "identity"argument tells ggplot to treat each value as an identity (i.e., not perform any transformations). - This chart can be useful for visualizing the estimated effects of different hair colours on length.
Last modified on 2024-06-16