我試圖用 ggplot2 制作箱線圖。
我必須使用我想要的格式制作箱線圖的代碼如下:
p <- ggplot(mg_data, aes(x=Treatment, y=CD68, color=Treatment))
geom_boxplot(mg_data, mapping=aes(x=Treatment, y=CD68))
p theme_classic() geom_jitter(shape=16, position=position_jitter(0.2))
我可以使用以下代碼制作回圈箱線圖:
variables <- mg_data %>%
select(10:17)
for(i in variables) {
print(ggplot(mg_data, aes(x = Treatment, y = i, color=Treatment))
geom_boxplot())
}
使用此代碼,我得到了箱線圖,但是它們沒有為 y 軸選擇的變數的名稱標簽,這與不使用 for 回圈時的原始代碼不同。我也不知道如何將格式化代碼添加到回圈中:
p theme_classic() geom_jitter(shape=16, position=position_jitter(0.2))
uj5u.com熱心網友回復:
這是一種方法。我已經使用內置資料集進行了測驗iris,只需更改資料名稱和選定的列即可。
suppressPackageStartupMessages({
library(dplyr)
library(ggplot2)
})
variables <- iris %>%
select(1:4) %>%
names()
for(i in variables) {
g <- ggplot(iris, aes(x = Species, y = get(i), color=Species))
geom_boxplot()
ylab(i)
print(g)
}
編輯
回答用戶TarJae的評論,在此轉載,因為答案比評論少洗掉:
您能否通過保存所有四個檔案進行擴展。非常感謝。
ggsave可以使用上面的代碼在回圈結束時使用指令保存繪圖。檔案名是變數名,繪圖是默認值,回傳值為last_plot().
for(i in variables) {
g <- ggplot(iris, aes(x = Species, y = get(i), color=Species))
geom_boxplot()
ylab(i)
print(g)
ggsave(paste0(i, ".png"), device = "png")
}
uj5u.com熱心網友回復:
嘗試這個:
variables <- mg_data %>%
colnames() %>%
`[`(10:17)
for (i in variables) {
print(ggplot(mg_data, aes(
x = Treatment, y = {{i}}, color = Treatment
))
geom_boxplot())
}
uj5u.com熱心網友回復:
另一種選擇是使用lapply. 它與使用回圈大致相同,但它隱藏了實際的回圈部分,并且可以使您的代碼看起來更干凈一些。
variables = iris %>%
select(1:4) %>%
names()
lapply(variables, function(x) {
ggplot(iris, aes(x = Species, y = get(x), color=Species))
geom_boxplot() ylab(x)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492614.html
