[英]Loop graphs ggplot y for x for different categories with linear regression, How to consequetively plot categories?
已編輯:我有一個大型數據庫,試圖隨着時間的推移重復評估能量消耗,目的是比較多個不同的變量(0/1,例如存在嚴重的頭部外傷與否)。 應該對數據庫中的所有可用變量重復圖形分析。 所有表都應導出到 PDF 文件。
目前我正在使用以下代碼:
library(tidyverse)
library(ggpmisc)
my_data %>%
pdf(file="Plots.pdf" )
print(colnames(my_data) %>%
map(function(x) my_data%>%
ggplot(aes(x = Day,
y = REE,
color=as_factor(x)))+
scale_x_continuous(breaks = c(0,2,4,6,8,10,12,14,16,18,20,22,24,26,28))+
scale_y_continuous(limits= c(0000,4000))+
geom_point()+
geom_smooth(method=lm,
se=TRUE,
size=2/10,
aes(group=as_factor(x)))+
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label),
after_stat(p.value.label),
sep = "*\", \"*")),
label.y="bottom", label.x="right")+
labs(x="Time [d]",
y="Resting Energy Expenditure [kcal]")+
scale_colour_grey(start=0.7,
end=0.3)+
theme_bw()
))
dev.off()
它生成包含所有圖形的 PDF 文件。 但是,它不會根據 as_factor(x) 進行分組/着色,並且所有數據點都歸入同一組。
是否有人對如何解決根據因子變量進行分類不起作用的問題有可能的解釋?
問題是您遍歷作為字符串的列名。 執行color=as.factor(x)
您正在將一個常量字符串映射到color
aes 上,即您正在執行類似color="foo"
的操作。 要告訴ggplot2
您想要 map 數據列,其名稱存儲在顏色 aes 上的x
中,您必須使用例如.data
代詞,即執行color=as.factor(.data[[x]])
。
使用基於mtcars
的最小表示:
注意:我個人建議將您的繪圖代碼放在單獨的 function 中,而不是將其作為匿名 function 傳遞給purrr::map
,如下所示。 使調試更容易,代碼更干凈。
library(tidyverse)
library(ggpmisc)
my_data <- mtcars
plot_fun <- function(x) {
ggplot(my_data, aes(
x = mpg,
y = hp,
color = as_factor(.data[[x]])
)) +
#scale_x_continuous(breaks = c(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28)) +
#scale_y_continuous(limits = c(0000, 4000)) +
geom_point() +
geom_smooth(
method = lm,
se = TRUE,
size = 2 / 10,
aes(group = as_factor(x))
) +
stat_poly_eq(aes(label = paste(after_stat(eq.label),
after_stat(rr.label),
after_stat(p.value.label),
sep = "*\", \"*"
)),
label.y = "bottom", label.x = "right"
) +
labs(
x = "Time [d]",
y = "Resting Energy Expenditure [kcal]"
) +
scale_colour_grey(
start = 0.7,
end = 0.3
) +
theme_bw()
}
cols <- c("cyl", "am", "gear") # colnames(my_data)
#pdf(file = "Plots.pdf")
purrr::map(cols, plot_fun)
#> [[1]]
#> `geom_smooth()` using formula 'y ~ x'
#>
#> [[2]]
#> `geom_smooth()` using formula 'y ~ x'
#>
#> [[3]]
#> `geom_smooth()` using formula 'y ~ x'
#dev.off()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.