Reputation: 33
I am trying to plot a bar plot that displays the fat composition of different vegetable oils. I tried plotting the type of oil on the y-axis and the fat amounts in the x-axis, so that each type of fat would be placed next to each other. Attempted Code:
ggplot(fats, aes(x=Fats, y=Oil, fill=Type))+
geom_bar(position = "fill")
This gave no results, with the error being
Error: stat_count() must not be used with a y aesthetic.
I then tried inserting only the x-axis but with poor results.
ggplot(fats, aes(x=Oil, fill=Type))+
geom_bar(position = "fill")
which gave me the following plot
What I expected was more like
The data is the following
df <- structure(list(row = 1:19, oil = structure(c(4L, 4L, 4L, 6L,
6L, 6L, 3L, 3L, 3L, 3L, 5L, 5L, 5L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Coconut",
"Palm", "Peanut", "Rapeseed", "Rice", "Sunflower"), class = "factor"),
fat = c(8L, 64L, 28L, 11L, 20L, 69L, 17L, 46L, 32L, 5L, 25L,
38L, 37L, 51L, 39L, 10L, 87L, 13L, 0L), type = structure(c(4L,
1L, 3L, 4L, 1L, 3L, 4L, 1L, 3L, 2L, 4L, 1L, 3L, 4L, 1L, 3L,
4L, 1L, 3L), .Label = c("Monounsaturated", "Other", "Polyunsaturated",
"Saturated"), class = "factor")), class = "data.frame", row.names = c(NA,
-19L))
##> df
## row oil fat type
## 1 1 Rapeseed 8 Saturated
## 2 2 Rapeseed 64 Monounsaturated
## 3 3 Rapeseed 28 Polyunsaturated
## 4 4 Sunflower 11 Saturated
## 5 5 Sunflower 20 Monounsaturated
## 6 6 Sunflower 69 Polyunsaturated
## 7 7 Peanut 17 Saturated
## 8 8 Peanut 46 Monounsaturated
## 9 9 Peanut 32 Polyunsaturated
## 10 10 Peanut 5 Other
## 11 11 Rice 25 Saturated
## 12 12 Rice 38 Monounsaturated
## 13 13 Rice 37 Polyunsaturated
## 14 14 Palm 51 Saturated
## 15 15 Palm 39 Monounsaturated
## 16 16 Palm 10 Polyunsaturated
## 17 17 Coconut 87 Saturated
## 18 18 Coconut 13 Monounsaturated
## 19 19 Coconut 0 Polyunsaturated
Upvotes: 2
Views: 168
Reputation: 16178
Alternatively, you can calculate percentage outside of ggplot
by using dplyr
for example and pass it into ggplot2
:
library(dplyr)
library(ggplot2)
df %>% group_by(oil) %>% mutate(Fat_percent = fat/sum(fat)) %>%
ggplot(aes(x = oil, y = Fat_percent, fill = type))+
geom_col()+
coord_flip()+
scale_y_continuous(labels = scales::percent, position = "right")+
theme(legend.position = "top")
Does it answer your question ?
Upvotes: 3