[英]Plot multiple distributions by year using ggplot Boxplot
我正在尝试在类似于此的箱线图中评估上述数据: https : //www.r-graph-gallery.com/89-box-and-scatter-plot-with-ggplot2.html
我希望 x 轴反映我的“年份”变量和每个箱线图来评估 8 种方法作为分布。 最后,我想确定与该分布相关的“Selected”变量,但目前我只想渲染这个东西!
我想出了如何编码我的 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("")
我看不到您的代码如何与数据集的屏幕截图相匹配。 然而,只是一个普遍的提示:ggplot 喜欢长格式的数据。 我建议您使用tidyr::reshape_long
或data.table::melt
重塑您的数据。 这样你会得到 3 列:年份、方法、值,其中前两列应该是一个因素。 然后可以在aes()
巧妙地将生成的数据集用作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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.