首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ggvoronoi按因子着色时,手动设置Voronio图的颜色

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

Stack Overflow用户
提问于 2020-02-13 01:24:12
回答 1查看 95关注 0票数 2

上午、下午或晚上。

代码语言:javascript
复制
# 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均值聚类的输出)对它们进行着色。我需要创建相当多的图,所以我在循环中运行它,如下所示:

代码语言:javascript
复制
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颜色选项。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-13 01:47:03

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

代码语言:javascript
复制
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')
  #
}

它回答了你的问题吗?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60193923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档