使用 ggvoronoi 按因子着色时手动设置 Voronio 图的颜色

Manually setting colours for Voronio plot when colouring by factor using ggvoronoi

上午、下午 或晚上。

# 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')
  #
}

它能回答您的问题吗?