从因子转换为数字时,boxplot显示不正确

问题描述 投票:1回答:1

我的图表无需使用比例即可正确显示我希望它看起来更好,所以我将因子转换为数字然后使用scale_x_continuous。但是,当我从因子转换为数字(How to convert a factor to an integer\numeric without a loss of information?)时,图表看起来不正确。我不能使用比例而不转换为数字。无论有没有这些lines ( main$U <- as.numeric(as.character(main$U))+ scale_x_continuous(name="Temperature", limits=c(0, 160)) ),请在下面运行示例代码。谢谢。

library("ggplot2")
library("plyr")

df<-data.frame(U = c(25, 25, 25, 25, 25, 85, 85, 85, 125, 125), 
               V =c(1.03, 1.06, 1.1,1.08,1.87,1.56,1.75,1.82, 1.85, 1.90), 
               type=c(2,2,2,2,2,2,2,2,2,2)) 

df1<-data.frame(U = c(25, 25,25,85, 85, 85, 85, 125, 125,125), 
                V =c(1.13, 1.24,1.3,1.17, 1.66,1.76,1.89, 1.90, 1.95,1.97), 
                type=c(5,5,5,5,5,5,5,5,5,5)) 

df2<-data.frame(U = c(25, 25, 25, 85, 85,85,125, 125,125), 
                V =c(1.03, 1.06, 1.56,1.75,1.68,1.71,1.82, 1.85,1.88), 
                type=c(7,7,7,7,7,7,7,7,7))

main <- rbind(df,df1,df2)
main$type <- as.factor(main$type)
main <- transform(main, type = revalue(type,c("2"="type2", "5"="type5", "7" = "type7")))
main$U <- as.factor(main$U)
main$U <- as.numeric(as.character(main$U))

ggplot(main, aes(U, V,color=type)) + 
  geom_boxplot(width=0.5/length(unique(main$type)), size=.3, position="identity") + 
  scale_x_continuous(name="Temperature", limits=c(0, 160))  
r ggplot2 boxplot
1个回答
2
投票

您必须在调用group时指定geom_boxplot,并保留图例,您可以使用color=factor(U)(即将U转换回来)。为了不丢失具有相同x值的组的信息,我认为最好先创建一个新的分组列。你获取所有独特的Utype对,并根据哪一行落入这些对中的哪一对来创建一个新变量。

main$U <- as.character(main$U)
main$type <- as.character(main$type)

grp_keys <- unique(as.matrix(main[, c("U", "type")]))
grp_inds <- 1:nrow(grp_keys)

main$grps <- apply(main, 1, function(x) {
  grp_inds[colSums(as.character(x[c("U", "type")]) == t(grp_keys)) == length(c("U", "type"))]
  })

然后,绘图(宽度调整,因为它看起来非常小,范围更高),

main$U <- as.numeric(as.character(main$U))
ggplot(main, aes(U, V,color=type)) + 
  geom_boxplot(aes(group = grps, color = type), width=20/length(unique(main$type)), size=.3, position="identity") +
  scale_x_continuous(name="Temperature", limits=c(0, 160))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.