【问题标题】:ggplot2 boxplot with geometric mean, and 90th and 10th percentilesggplot2 具有几何平均值的箱线图,以及第 90 和第 10 个百分位数
【发布时间】:2016-05-07 21:11:12
【问题描述】:

我需要创建一个独特的箱线图。我希望它代表几何平均值而不是中位数,并且盒子的顶部和底部是第 90 个和第 10 个百分位数。我找到了有关如何添加均值和 sd 以及如何在绘图上扩展 wiskers 的信息,但没有找到如何更改基本统计数据的信息。我想使用 ggplot2,因为我对它很熟悉,但我对任何事情都持开放态度。

我正在使用以下代码按年份绘制粪便大肠菌群数据:

library(psych)
library(dplyr)
library(zoo)
library(caTools)
library(ggplot2)
library(stats)

setwd("H:/MWQSampleData/GrowingAreaRawData")

setAs("character", "myDate", function(from) as.Date(from, format = "%m/%d/%Y"))

RawData <- read.csv("VaughnBay1989.csv", header = TRUE, colClasses = 
            c("factor", "factor", "myDate", "numeric", "factor", "numeric", "numeric","numeric"))

GrowingAreaYrSummary <- RawData %>%
  select(Year, FecalColiform) %>%
  group_by(Year)



Graph <- ggplot(GrowingAreaYrSummary, aes(x=Year, y=FecalColiform))
  geom_boxplot(outlier.shape = NA) +
  theme(axis.text.y = element_text(face = "bold", angle = 45, size = 14), 
        axis.text.x = element_text(face = "bold", angle = 45, size = 14, vjust = -0.005),
        panel.background = element_rect(fill = "ivory2"), 
        panel.grid.major = element_line(colour = "gray88"),
        plot.title = element_text(size = 18, face = "bold", vjust = -4),
        axis.title.y = element_text(size = 16, face = "bold"),
        axis.title.x = element_text(size = 16, face = "bold", vjust = -0.5),
        axis.ticks.x = element_line(size = 1.5, colour = "black"),
        panel.border = element_rect(colour = "black", fill = NA, size = 1)) +
  scale_y_continuous(breaks=seq(0,50,5), limits=c(0,50)) +
  geom_smooth(method="loess", se="TRUE", aes(group=1)) +
  ggtitle("Vaughn Bay Growing Area \n Fecal Coliform 1989 - 2015") +
  ylab("Fecal Coliform (fc/100 ml)") +
  xlab("Year") +
  annotate("text", x=10, y=43, label="Outliers Excluded \n from Graph")

Graph

我想制作相同的图表,但使用新组件。任何见解都值得赞赏。谢谢!

【问题讨论】:

  • 向下滚动到本页底部 (docs.ggplot2.org/dev/geom_boxplot.html) 它解释了如何操作
  • 如果您需要比 MLavoie 的链接更多的帮助,那么您应该创建一个可重现的最小示例 (see tips here)。我们没有您的 CSV(我们也不应该需要它),最好使用一些内置数据或模拟一个小型数据集来说明问题。我们也可能不需要 5 个包和 10 个主题自定义来传达主要思想。

标签: r ggplot2 boxplot


【解决方案1】:

你可以编写一个特殊用途的函数来传递给stat_summary

# Return the desired percentiles plus the geometric mean
bp.vals <- function(x, probs=c(0.1, 0.25, 0.75, .9)) {
  r <- quantile(x, probs=probs , na.rm=TRUE)
  r = c(r[1:2], exp(mean(log(x))), r[3:4])
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

# Sample usage of the function with the built-in mtcars data frame
ggplot(mtcars, aes(x=factor(cyl), y=mpg)) +
  stat_summary(fun.data=bp.vals, geom="boxplot")

我有一个类似的函数用于箱线图中的自定义百分位数,我最初是从this SO answer 改编的。

【讨论】:

  • 谢谢,很有帮助!
猜你喜欢
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-08-07
  • 2021-12-25
  • 1970-01-01
  • 2021-01-21
  • 2014-03-25
  • 2021-11-25
相关资源
最近更新 更多