GGPlot2 Boxplot仅显示扁平线条

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

我已经工作了几个小时,似乎无法做到这一点。箱形图只给我平直的线条,它让我疯狂。我得到相同的输入,有或没有因子功能

ggplot(df2,aes(x = factor(Location),y=Final.Result)) + geom_boxplot()

解决了!有一些数据值,例如“<0.005”,R将其作为字符串获取并将所有内容转换为因子。

r ggplot2 boxplot
3个回答
4
投票

你有这些线,因为你的数据框中的变量Final.Result是因子而不是数字(你可以用函数str()检查它)。

> str(df2)
'data.frame':   66 obs. of  3 variables:
 $ Location    : Factor w/ 17 levels "BOON KENG RD BLK 6 (DS)",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Parameter   : Factor w/ 54 levels "Aluminium","Ammonia (as N)",..: 37 37 37 37 37 37 37 37 37 37 ...
 $ Final.Result: Factor w/ 677 levels "< 0.0005","< 0.001",..: 645 644 654 653 647 643 647 647 646 646 ...

尝试将这些值转换为数字(如df2中没有非数值)。这仅适用于df2,但如果您的整个数据框具有那些"< 0.0005","< 0.001"值,您应该决定如何处理它们(用NA或一些小常量替换)。

df2$Final.Result2<-as.numeric(as.character(df2$Final.Result))
ggplot(df2,aes(x = factor(Location),y=Final.Result2)) + geom_boxplot()

2
投票

这个答案只与问题的标题有关,但如果我谷歌“ggplot2 boxplot only lines”这个问题排在首位,并且该搜索字词没有其他有用的搜索结果,所以我觉得它很适合这里:

Box Plots仅在您将数量指定为y美学时才有效。

相比

 ggplot(mtcars, aes(x = factor(cyl), y = disp)) + geom_boxplot()

这给出了正确的箱形图

 ggplot(mtcars, aes(y = factor(cyl), x = disp)) + geom_boxplot()

它只提供线条而不是箱形图。

要获得水平箱形图,请使用coord_flip()

 ggplot(mtcars, aes(x = factor(cyl), y = disp)) + 
   geom_boxplot() + coord_flip()


0
投票

你得到扁平线而不是盒子的另一个原因是你总结了表中的数值(例如计算平均值,中位数等),现在boxplot()只能看到一个值。

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