R 错误:stat_count()不能与y组合使用

R 错误:stat_count()不能与y组合使用,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我试图绘制一个条形图,显示不同植物油的脂肪成分。我试着在y轴上画出油的类型,在x轴上画出脂肪的数量,这样每种类型的脂肪都会挨着放。 尝试的代码: ggplot(fats, aes(x=Fats, y=Oil, fill=Type))+ geom_bar(position = "fill") 这没有给出任何结果,错误为 错误:stat\u count()不能与y组合使用。 然后我尝试只插入x轴,但效果不佳 ggplot(fats, aes(x=Oil, fill=Type))+ geo

我试图绘制一个条形图,显示不同植物油的脂肪成分。我试着在y轴上画出油的类型,在x轴上画出脂肪的数量,这样每种类型的脂肪都会挨着放。 尝试的代码:

ggplot(fats, aes(x=Fats, y=Oil, fill=Type))+
  geom_bar(position = "fill")
这没有给出任何结果,错误为

错误:stat\u count()不能与y组合使用。

然后我尝试只插入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
df
##行油脂型
##1 1油菜籽8饱和
##2 2油菜64单不饱和脂肪酸
##3 3油菜籽28多不饱和脂肪酸
##4向日葵11饱和
##5向日葵20单不饱和脂肪酸
##6向日葵69多不饱和脂肪酸
##7花生17饱和
##8花生46单不饱和脂肪酸
##9花生32多不饱和脂肪酸
##10 10花生5其他
##11米25饱和
##12大米38单不饱和脂肪酸
##13 13大米37多不饱和脂肪酸
##14棕榈51饱和
##15棕榈39单不饱和脂肪酸
##16棕榈10多不饱和脂肪酸
##17椰子87饱和
##18椰子13单不饱和脂肪酸
##19 19 0多不饱和脂肪酸

或者,您可以使用
dplyr
计算
ggplot
之外的百分比,并将其传递到
ggplot2

库(dplyr)
图书馆(GG2)
df%>%组(油)%>%突变(脂肪百分比=脂肪/总和(脂肪))%>%
ggplot(aes(x=油,y=脂肪百分比,填充=类型))+
geom_col()+
coord_flip()+
连续缩放(标签=缩放::百分比,位置=“右”)+
主题(legend.position=“top”)


它回答了您的问题吗?

可能是因为您必须设置
stat=“identity”
或使用
geom\u col()
(默认设置),但由于您没有提供可复制的示例,因此无法回答。参见同意@j3ypi。试一试:
ggplot(fats,aes(x=fats,y=Oil,fill=Type))+geom_-bar(stat=“identity”,position=“fill”)