我如何將所有傳說保留在情節中?下面是散點圖的一個例子。它僅在 x > 0.5 時列印。但我想展示所有的傳說。

library(tidyverse)
for (iter in 1:5)
{
# generate 5 random points
tbl <- tibble(x = runif(5),
y = runif(5),
class = c("A", "B", "C", "D", "E"))
# print if x > 0.5
p <- ggplot(data = tbl %>% filter(x > 0.5),
aes(x = x,
y = y,
color = class))
geom_point(size = 5)
scale_fill_manual(labels = c("A", "B", "C", "D", "E"),
values = c("Grey", "Red", "Green", "Blue", "Yellow"),
drop = FALSE)
theme_bw()
theme(aspect.ratio = 1)
xlim(0, 1)
ylim(0, 1)
ggsave(p,
filename = paste0(iter, ".png"))
}
uj5u.com熱心網友回復:
您可以在以下情況下執行此操作:
- 你將
class變數設定為factor - 使用
scale_colour_manual代替scale_fill_manual. 如果您想使用 ggplot 調色板中的默認顏色,您可以使用scale_colour_descrete,就像我的代碼一樣。
library(tidyverse)
set.seed(1) # for reproducibility
plots <- lapply(1:5, function(iter){
# generate 5 random points
tbl <- tibble(x = runif(5),
y = runif(5),
class = factor(c("A", "B", "C", "D", "E")))
# print if x > 0.5
p <- ggplot(data = tbl %>% filter(x > 0.5),
aes(x = x,
y = y,
color = class))
geom_point(size = 5)
scale_colour_discrete(drop = FALSE)
theme_bw()
theme(aspect.ratio = 1)
xlim(0, 1)
ylim(0, 1)
ggsave(p, filename = paste0(iter, ".png"))
p
})
# visualize them all together
cowplot::plot_grid(plotlist = plots)

PS:我使用lapply而不是for回圈,通常在可能的情況下,R 用戶更喜歡使用它。
uj5u.com熱心網友回復:
您可以將值更改為 NA,而不是過濾掉資料:
library(tidyverse)
for (iter in 1:5)
{
# generate 5 random points
tbl <- tibble(x = runif(5),
y = runif(5),
class = c("A", "B", "C", "D", "E"))
# print if x > 0.5
p <- ggplot(data = tbl %>% mutate(y = if_else(x > 0.5, y, NA_real_)),
aes(x = x,
y = y,
color = class))
geom_point(size = 5)
scale_fill_manual(labels = c("A", "B", "C", "D", "E"),
values = c("Grey", "Red", "Green", "Blue", "Yellow"),
drop = FALSE)
theme_bw()
theme(aspect.ratio = 1)
xlim(0, 1)
ylim(0, 1)
ggsave(p,
filename = paste0(iter, ".png"))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/360787.html
