使用 ggplot Boxplot 按年份绘制多个分布

ark*_*rks 0 r ggplot2 boxplot

在此输入图像描述

我正在尝试在类似于此的箱线图中评估上述数据:https://www.r-graph-gallery.com/89-box-and-scatter-plot-with-ggplot2.html

文本

我希望 x 轴反映我的“年份”变量,并且每个箱线图将 8 种方法评估为分布。最终我想确定与该分布相关的“选定”变量,但目前我只想渲染这个东西!

我弄清楚如何编码我的 y 变量,但无论我尝试什么,我都会遇到各种错误。我认为 PY 需要是 as.factor 但我已经尝试过一些这样的代码,但我只是得到了其他错误。

无论如何,这是我的代码(发送帮助):

# Libraries

library(tidyverse)
library(hrbrthemes)
library(viridis)
library(ggplot2)
library(readxl) # For reading in Excel files
library(lubridate) # For handling dates
library(dplyr) # for mutate and pipe functions

# Path to current and prior data folders
DataPath_Current <- "C:/R Projects/Box Plot Test"

Ult_sum <- read_excel(path = paste0(DataPath_Current, "/estimate.XLSX"), 
                                           sheet = "Sheet1",
                                           range = "A2:J12",
                                           guess_max = 100)

# just want to see what my table looks like
Ult_sum
# create a dataset - the below is code I commented out

# data <- data.frame(
# name=c(Ult_sum[,1]),
#     value=c(Ult_sum[1:11,2:8])
#)

value <- Ult_sum[2,]

  # Plot
Ult_sum %>%
  ggplot( aes(x= Year, y= value, fill=Year)) +
  geom_boxplot() +
  scale_fill_viridis(discrete = TRUE, alpha=0.6) +
  geom_jitter(color="black", size=0.4, alpha=0.9) +
  theme_ipsum() +
  theme(
    legend.position="none",
    plot.title = element_text(size=11)
  ) +
  ggtitle("A boxplot with jitter") +
  xlab("")
Run Code Online (Sandbox Code Playgroud)

Hei*_*N3r 5

我不明白您的代码如何与数据集的屏幕截图相匹配。然而,只是一个一般提示:ggplot 喜欢长格式的数据。tidyr::reshape_long我建议您使用order重塑数据data.table::melt。这样你就得到了 3 列:年份、方法、值,其中前两列应该是一个因素。aes()然后可以在as中巧妙地使用生成的数据集aes(x=year, y=value, fill=method)

编辑:添加了一个示例。这是你想要的吗?

library(data.table)
library(magrittr) 
library(ggplot2)
DT <- data.table(year = factor(rep(2010:2014, 10)),
                 method1 = rnorm(50),
                 method2 = rnorm(50),
                 method3 = rnorm(50))

DT_long <- DT %>% melt(id.vars = "year")

ggplot(DT_long, aes(x = year, y = value, fill = variable)) +
geom_boxplot()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 好的,所以在上面的代码中只需删除“fill=variable”即可。然后,将使用所有方法按年份计算的所有值来计算箱线图。背景是你无法再通过什么方法分辨出最小值、最大值、中值干。如果这不是您想要的,恐怕我不完全理解您的问题。 (2认同)