Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

ggplot2 - Plot percentage of factor levels in R ggplot

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to indicate stat = "identity" in the call to geom_bar.


ggplot(mydata, aes(x = factor(use))) + 
geom_bar(stat = "identity", aes(y = (quantity)/sum(quantity))) +
coord_flip() + scale_y_continuous(labels = scales::percent)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...