Rya*_*ugh 8 r median ggplot2 boxplot
所以,我有一个相当大的数据集(Dropbox:csv文件),我正在尝试使用它geom_boxplot.以下产生了似乎合理的情节:
require(reshape2)
require(ggplot2)
require(scales)
require(grid)
require(gridExtra)
df <- read.csv("\\Downloads\\boxplot.csv", na.strings = "*")
df$year <- factor(df$year, levels = c(2010,2011,2012,2013,2014), labels = c(2010,2011,2012,2013,2014))
d <- ggplot(data = df, aes(x = year, y = value)) +
geom_boxplot(aes(fill = station)) +
facet_grid(station~.) +
scale_y_continuous(limits = c(0, 15)) +
theme(legend.position = "none"))
d
Run Code Online (Sandbox Code Playgroud)
然而,当你深入挖掘时,问题就会蔓延开来.当我用它们的值标记boxplot medians时,会产生以下图表.
df.m <- aggregate(value~year+station, data = df, FUN = function(x) median(x))
d <- d + geom_text(data = df.m, aes(x = year, y = value, label = value))
d
Run Code Online (Sandbox Code Playgroud)

由geom_boxplot绘制的中位数根本不在中位数.标签以正确的y轴值绘制,但箱图的中间铰链绝对不在中位数.我已经被这几天困扰了.
这是什么原因?如何用正确的中位数生成这种类型的显示?如何调试或诊断该图?
这个问题的解决方案是在应用中scale_y_continuous.ggplot2将按以下顺序执行操作:
在这种情况下,因为调用了比例变换,所以ggplot2排除了用于统计计算boxplot铰链的比例限制之外的数据.然而,由aggregate函数计算并在geom_text指令中使用的中位数将使用整个数据集.这可能导致不同的中间铰链和文本标签.
解决方案是省略scale_y_continuous指令,而是使用:
d <- ggplot(data = df, aes(x = year, y = value)) +
geom_boxplot(aes(fill = station)) +
facet_grid(station~.) +
theme(legend.position = "none")) +
coord_cartesian(y = c(0,15))
Run Code Online (Sandbox Code Playgroud)
这允许ggplot2使用整个数据集计算boxplot铰链统计数据,同时限制图的绘图大小.
| 归档时间: |
|
| 查看次数: |
1375 次 |
| 最近记录: |