R ggplot:堆叠条形图超出值

R ggplot:堆叠条形图超出值,r,ggplot2,R,Ggplot2,在某些情况下,堆叠条形图会创建超出值的条形图 以下是显示问题的可复制示例: # creating some dataframe for the example eg <- matrix(nrow=4, ncol=3) eg[,1] <- c('a', 'b', 'a', 'b') eg[,2] <- c('catA', 'catA', 'catB', 'catB') eg[,3] <- c(0.7, 0.3, 0.8, 0.4) colnames(eg) <- c(

在某些情况下,堆叠条形图会创建超出值的条形图

以下是显示问题的可复制示例:

# creating some dataframe for the example
eg <- matrix(nrow=4, ncol=3)
eg[,1] <- c('a', 'b', 'a', 'b')
eg[,2] <- c('catA', 'catA', 'catB', 'catB')
eg[,3] <- c(0.7, 0.3, 0.8, 0.4)
colnames(eg) <- c('ID', 'type', 'proportion')
eg <- as.data.frame(eg)

# plotting
ggplot (data=eg, aes (x=ID, y=proportion, fill=type)) +
  geom_bar(stat='identity')
#为示例创建一些数据帧

例如尝试在
几何图形栏中添加一个位置参数,如下所示:

ggplot (data=eg, aes (x=ID, y=proportion, fill=type)) +
  geom_bar(stat='identity', position = position_dodge())

问题在于比例被强制转换为字符矩阵

eg <- matrix(nrow=4, ncol=3)
eg[,1] <- c('a', 'b', 'a', 'b')
eg[,2] <- c('catA', 'catA', 'catB', 'catB')
# this part is the problem
eg[,3] <- c(0.7, 0.3, 0.8, 0.4)
colnames(eg) <- c('ID', 'type', 'proportion')
eg <- as.data.frame(eg)
str(eg)

例如,只是一个友好的提示,
geom_bar(stat=“identity”,…)
是等价表达的
geom_col(…)
eg <- data.frame(
    ID <- c('a', 'b', 'a', 'b'),
    type <- c('catA', 'catA', 'catB', 'catB'),
    proportion <- c(0.7, 0.3, 0.8, 0.4)
    )

ggplot (data=eg, aes (x=ID, y=proportion, fill=type)) +
  geom_bar(stat='identity')