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

问题描述 投票:2回答:1

早上,下午或晚上。

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

这给了我以下(很棒的)情节:enter image description here

此问题为彩色。我希望情节之间保持一致。例如,对于永远的图,聚类2将是蓝色,聚类3 =红色,等等。

我很困惑在这里使用多个ggplot颜色选项来确保一致性。非常感谢!!

[早晨,下午或晚上。 #可重现数据df

r ggplot2 colors voronoi
1个回答
2
投票

您可以定义一个向量来将颜色归因于“ cluster”变量的每个值,然后将它们传递到values =函数的参数scale_fill_manual中,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.