上午、下午或晚上。
# 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颜色选项。非常感谢!
发布于 2020-02-13 01:47:03
您可以定义一个向量来为"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')
#
}

和

它回答了你的问题吗?
https://stackoverflow.com/questions/60193923
复制相似问题