Ошибка: stat_count () не должен использоваться с любым эстетическим - PullRequest
2 голосов
/ 29 марта 2020

Я пытаюсь построить гистограмму, которая отображает состав жира различных растительных масел. Я попытался построить тип масла на оси Y и количество жира на оси X, чтобы каждый тип жира располагался рядом друг с другом. Попытка кода:

ggplot(fats, aes(x=Fats, y=Oil, fill=Type))+
  geom_bar(position = "fill")

Это не дало никаких результатов, с ошибкой

Error: stat_count() must not be used with a y aesthetic.

Затем я попытался вставить только ось X, но с плохими результатами.

ggplot(fats, aes(x=Oil, fill=Type))+
   geom_bar(position = "fill")

, который дал мне следующий сюжет

Неудачный сюжет

То, что я ожидал, было больше похоже на

Ожидаемый участок

Данные следующие

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

1 Ответ

2 голосов
/ 29 марта 2020

Кроме того, вы можете рассчитать процент за пределами ggplot, используя, например, dplyr и передать его в 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")

enter image description here

Это отвечает на ваш вопрос?

...