gpt4 book ai didi

R ggplot geom_bar 错误 : Discrete value supplied to continuous scale

转载 作者:行者123 更新时间:2023-12-05 00:20:39 25 4
gpt4 key购买 nike

我有 4 个实验组的比例响应数据,每个组计算了 2 个不同的统计数据。我想要下图(我可以实现):
enter image description here
我使用以下代码获得此图:

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() 来转换我的统计变量和无数其他选择,但无济于事。如果有人能帮助我解决这个问题和/或解释导致它的原因,我将不胜感激。

最佳答案

问题是不必要的使用 cbinddata.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

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

关于R ggplot geom_bar 错误 : Discrete value supplied to continuous scale,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33819440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com