ggplot(resultslog, aes(log2(a))) + geomfreqpoly(bins = 100) + theme_classic() Make y…
- User
ggplot(results_log, aes(log2(a))) + geom_freqpoly(bins = 100) + theme_classic() Make y axis percents?
Assistant
That's a great question! To change the y-axis of a geom_freqpoly plot from counts to percentages in ggplot2, you need to do two things:Specify a new calculated aesthetic for the y-axis within geom_freqpoly.Use a scale function to format the y-axis labels as percentages.You'll typically need the scales package for the percentage formatting.Here is the modified R code:R# You might need to install and load the scales package if you haven't already
install.packages("scales")
library(scales)
ggplot(results_log, aes(log2(a))) + geom_freqpoly( # 1. Calculate proportion: count in bin / total count aes(y = after_stat(count / sum(count))), bins = 100 ) +
2. Format the y-axis labels as percentages
scale_y_continuous(labels = percent) + labs(y = "Percentage") + # Optional: Change the axis title theme_classic() Key Changes ExplainedOriginal CodeModified CodeExplanationgeom_freqpoly(bins = 100)geom_freqpoly(aes(y = after_stat(count / sum(count))), bins = 100)This tells ggplot2 to calculate the proportion for the y-axis. after_stat(count) is the number of observations in a bin, and sum(count) is the total number of observations (the sum of all bin counts).scale_y_continuous(labels = percent)This function, from the scales package, takes the calculated proportions (which are between 0 and 1) and formats them as percentage strings (e.g., 0.05 becomes 5%).labs(y = "Percentage")While optional, it's good practice to rename the y-axis label to reflect the change from "count" to "percentage."Export to Sheets