Chr*_* Z. 4 r ggplot2 geom-bar
我有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')
Run Code Online (Sandbox Code Playgroud)
但是,当我通过添加代码行来更改y轴的限制(由于我有比例,因此更改为[0,1])时:
+ scale_y_continuous(limits=c(0, 1))
Run Code Online (Sandbox Code Playgroud)
我懂了
Error: Discrete value supplied to continuous scale
Run Code Online (Sandbox Code Playgroud)
所以我知道这意味着我有一个非连续变量。我尝试通过使用as.numeric()和无数其他选项来转换我的统计变量,但无济于事。如果有人可以帮助我解决这个问题和/或解释造成问题的原因,我将非常感激。
问题是cbind内部不必要的使用data.frame。cbind创建一个矩阵。矩阵必须具有相同模式的所有值(数字,字符等)。由于至少有一个变量(在这种情况下为两个)是字符模式,因此也要cbind强制转换Val为字符。data.frame将三个字符变量转换为因数。无论哪种方式,Val都是离散(分类)值而不是数字,使用会导致错误scale_y_continuous。
更改为dfm2 <- data.frame(Group,Statistic,Val),错误将消失。
您可以检查cbind和data.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
Run Code Online (Sandbox Code Playgroud)
如果您不想data.frame将字符串转换为因数,请添加参数stringsAsFactors=FALSE。