I have a table of use of vehicles where each record shows how many vehicles are for each kind of use.
I need to plot the percentage of vehicles for each use. Below I provide sample data:
use <- as.factor('private’, 'comercial', 'ambulance’, 'private’, 'comercial')
quantity <- c(2,1,4,6,1)
mydata <- data.frame(use, quantity)
In this case there should be private: 8, comercial: 2 and ambulance: 4
I have tried the following but I think that it counts the records and not the vehicles (private: 2, comercial: 2 and ambulance: 1)
library(scales)
library(ggplot2)
ggplot(mydata, aes(x = factor(use))) + geom_bar(aes(y = (..count..)/sum(..count..))) + coord_flip() +
scale_y_continuous(labels = scales::percent)
If i change the code:
ggplot(mydata, aes(x = factor(use))) + geom_bar(aes(y = (quantity)/sum(quantity))) + coord_flip() +
scale_y_continuous(labels = scales::percent)
I receive this error:
Error: stat_count() can only have an x or y aesthetic.
question from:
https://stackoverflow.com/questions/65872146/plot-percentage-of-factor-levels-in-r-ggplot 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…