gpt4 book ai didi

r - 错误 : stat_count() must not be used with a y aesthetic

转载 作者:行者123 更新时间:2023-12-04 10:19:41 26 4
gpt4 key购买 nike

我试图绘制一个条形图,显示不同植物油的脂肪成分。我尝试在 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")

这给了我以下情节

Unsuccessful Plot

我的预期更像是

Expected plot

数据如下
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

最佳答案

或者,您可以计算 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

它回答你的问题吗?

关于r - 错误 : stat_count() must not be used with a y aesthetic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60916655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com