R 按数据框中的百分比填充ggplot中的几何图形栏

R 按数据框中的百分比填充ggplot中的几何图形栏,r,ggplot2,bar-chart,fill,geom-bar,R,Ggplot2,Bar Chart,Fill,Geom Bar,我试图创建一个条形图,根据第一行(0.3181555,这是一个百分比)的平均值,用一种颜色填充条形图,用另一种颜色(0.6818445,第2行,第3列)填充条形图的其余部分,以获得从0到1的条形图。这是我的数据: View(int) Lower_Conf Upper_Conf Mean Lower_Pred Upper_Pred 1 0.3154548 0.3208561 0.3181555 0.3125413 0.3237696 2 0.6845452 0.6791

我试图创建一个条形图,根据第一行(0.3181555,这是一个百分比)的平均值,用一种颜色填充条形图,用另一种颜色(0.6818445,第2行,第3列)填充条形图的其余部分,以获得从0到1的条形图。这是我的数据:

View(int)

   Lower_Conf Upper_Conf   Mean   Lower_Pred Upper_Pred
1  0.3154548  0.3208561 0.3181555  0.3125413  0.3237696
2  0.6845452  0.6791439 0.6818445  0.6874587  0.6762304
我的代码是这样的:

ggplot(int,aes(x=1, y=int[1,3],fill=factor(Mean)))+
  geom_bar(position="fill", stat = "identity", width = 1.2)
我知道这是不对的,因为当我说
fill=factor(Mean)
时,它只是用一种颜色填充了50%的条,其余的用另一种颜色填充,我知道这是因为我用“级别”填充一个条,而我只有两个(因为我的数据中只有两个数字)。但是我不知道如何用我的数据框中的值填充。

我认为这可以帮助您(您也可以过滤特定变量,如您想要的平均值,这里我包括了数据中的所有变量):

library(重塑2)
图书馆(GG2)
#资料
df
library(reshape2)
library(ggplot2)
#Data
df <- structure(list(Lower_Conf = c(0.3154548, 0.6845452), Upper_Conf = c(0.3208561, 
0.6791439), Mean = c(0.3181555, 0.6818445), Lower_Pred = c(0.3125413, 
0.6874587), Upper_Pred = c(0.3237696, 0.6762304)), class = "data.frame", row.names = c("1", 
"2"))
#Create id per row
df$id <- 1:dim(df)[1]
#Melt
df.melted <- melt(df,id.vars = 'id')
df.melted$id <- factor(df.melted$id)
df.melted$id <- relevel(df.melted$id,ref = '2')
#Plot
ggplot(df.melted,aes(x=variable,y=value,fill=id,label=round(value,3)))+
  geom_bar(stat = 'identity')+
  geom_text(position = position_stack(vjust=0.5))+
  scale_fill_manual(values=c('cyan3','tomato'),guide = guide_legend(reverse=TRUE))