早上、下午 或晚上。
# Reproducible data
df <- quakes[1:20, 1:2]
df$years <- as.factor(rep(c("2000","2020"), each=10))
df$cluster <- as.factor(c("1","1","1","1","1","1","2","2","2","2",
"2","2","2","2","2","3","3","3","3","3"))
我正在使用 GPS 数据创建 voronoi 图并按一个因子(k 均值聚类的输出)对它们进行着色。我需要创建相当多的绘图,因此我在循环中运行它,如下所示:
years <- levels(df$years)
library(dplyr)
library(ggplot2)
library(ggvoronoi)
for(i in years){
#
single_year <- df %>%
filter(years == i)
#
#
plot <- ggplot(single_year,
aes(x=lat,
y=long)) +
#
geom_voronoi(aes(fill=(cluster))) +
#
stat_voronoi(geom="path" )+
#
geom_point() +
#
labs(title = paste(i))
#
#
ggsave(paste0(i,".jpeg"), plot = last_plot(), # Watch out for the SAVE!!!
device = 'jpeg')
#
}
这个问题是彩色的。我希望情节之间保持一致性。例如,在绘图中,簇 2 为蓝色,簇 3 = 红色,等等。
我很困惑在这里使用众多 ggplot 颜色选项中的哪一个来确保一致性。非常感谢!!
最佳答案
您可以定义一个向量,为“cluster”变量的每个值赋予颜色,然后将它们传递到 scale_fill_manual
函数的参数 values =
中,如以下:
library(ggplot2)
library(ggvoronoi)
library(dplyr)
for(i in df$years){
#
col = c("1" = "green", "2" = "blue", "3" = "red")
single_year <- df %>%
filter(years == i)
#
#
plot <- ggplot(single_year,
aes(x=lat,
y=long)) +
#
geom_voronoi(aes(fill = cluster)) +
#
stat_voronoi(geom="path" )+
#
geom_point() +
#
labs(title = paste(i))+
scale_fill_manual(values = col)
#
#
ggsave(paste0(i,".jpeg"), plot = last_plot(), # Watch out for the SAVE!!!
device = 'jpeg')
#
}
它能回答你的问题吗?
关于r - 使用 gg voronoi 按因子着色时手动设置 Voronoi 图的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193923/