R ggplot geom_bar Error: Discrete value supplied to continuous scale

R ggplot geom_bar Error: Discrete value supplied to continuous scale

我有 4 个实验组的比例响应数据,每个组计算了 2 个不同的统计数据。我想要下图(我能实现):

我用下面的代码得到这张图:

Group<-c('a','b','c','d','a','b','c','d')
Statistic<-c('Mean','Mean','Mean','Mean','d','d','d','d')
Val<-c(.75,.83,.79,.69,.5,.02,.1,.3)
dfm2<-data.frame(cbind(Group,Statistic,Val)) 
ggplot(dfm2,aes(x = Group,y = Val)) +    
 geom_bar(aes(fill = Statistic),position = dodge',stat='identity')

但是,当我通过添加以下代码行更改 y 轴的限制(更改为 [0,1],因为我有比例)时:

+ scale_y_continuous(limits=c(0, 1))

我明白了

Error: Discrete value supplied to continuous scale

所以我明白这意味着我有一个非连续变量。我曾尝试使用 as.numeric() 和无数其他选项来转换我的 Statistic 变量,但无济于事。如果有人能帮助我解决这个问题and/or 解释是什么原因造成的,我将不胜感激。

问题是在 data.frame 中不必要地使用了 cbindcbind 创建一个矩阵。矩阵必须具有相同模式(数字、字符等)的所有值。由于至少有一个变量(在本例中为两个)是字符模式,因此 cbind 也将 Val 强制转换为字符模式。 data.frame 将三个字符变量转换为因子。无论哪种方式,Val 都是离散(分类)值而不是数字,因此在您使用 scale_y_continuous 时会导致错误。

更改为 dfm2 <- data.frame(Group,Statistic,Val) 错误将消失。

您可以查看cbinddata.frame对数据类型的影响,如下所示:

cbind(Group, Statistic, Val)

     Group Statistic Val   
[1,] "a"   "Mean"    "0.75"
[2,] "b"   "Mean"    "0.83"
...
[7,] "c"   "d"       "0.1" 
[8,] "d"   "d"       "0.3" 

dfm2<-data.frame(cbind(Group,Statistic,Val))
str(dfm2)

'data.frame':   8 obs. of  3 variables:
$ Group    : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4
$ Statistic: Factor w/ 2 levels "d","Mean": 2 2 2 2 1 1 1 1
$ Val      : Factor w/ 8 levels "0.02","0.1","0.3",..: 6 8 7 5 4 1 2 3

dfm2 <- data.frame(Group,Statistic,Val)
str(dfm2)

'data.frame':   8 obs. of  3 variables:
$ Group    : Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4
$ Statistic: Factor w/ 2 levels "d","Mean": 2 2 2 2 1 1 1 1
$ Val      : num  0.75 0.83 0.79 0.69 0.5 0.02 0.1 0.3

如果您不想 data.frame 将字符串转换为因子,请添加参数 stringsAsFactors=FALSE.

试试下面的方法。

ggplot(dfm2,aes(x = Group,y = as.numeric(as.character(Val)))) +    
  geom_bar(aes(fill = Statistic),position = 'dodge',stat='identity')+
  scale_y_continuous(limits=c(0, 1))