【问题标题】:GGPlot2 Boxplot only shows flat linesGGPlot2 Boxplot 只显示平线
【发布时间】:2013-12-30 14:43:10
【问题描述】:

我已经为此工作了好几个小时,似乎无法做到这一点。箱线图只给了我平坦的垂直线,这让我发疯。无论有无因子函数,我都会得到相同的输入

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

解决了!有一些数据值,例如“

【问题讨论】:

  • 请将运行 dput(df2) 的结果粘贴到您的问题中。
  • 并包含生成您现在拥有的情节的代码:stackoverflow.com/questions/5963269/…
  • 这是一个非常棒的列表。这是pastebin链接。 pastebin.com/v1KRb6UM
  • @PaulHiemstra 在屏幕截图中,但这里是 ggplot(df2,aes(x = factor(Location),y=Final.Result)) + geom_boxplot()
  • 我建议将代码编辑到您的问题中。此外,如果您的输入数据很大,您可以为我们提供一个适当小的子集,它仍然会重现问题。您甚至可以创建虚拟数据。最后,您的输入数据看起来并没有那么大,我建议将其粘贴到您的问题中(这样会很聪明地显示什么),以便以后保持数据可用。

标签: r ggplot2 boxplot


【解决方案1】:

您得到这些行是因为数据框中的变量 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 但如果您的整个数据框具有这些 "&lt; 0.0005","&lt; 0.001" 值,您应该决定如何处理它们(替换为 NA 或一些小常数)。

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

【讨论】:

  • 这可能是真正的问题,我的解决方案不知何故也执行了这种转换。
  • @PaulHiemstra 您删除的解决方案也能正常工作,非常感谢!! :D
【解决方案2】:

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

箱线图仅在您将数量指定为 y aestetic 时才有效。

编辑:从 ggplot 3.3.0 开始,有 orientation= 参数允许 改变方向。 See the ggplot NEWS on this

比较

 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()

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多