重置 ggplot 刻面的每一列中的颜色

Resetting the color in each column of ggplot facets

我有一个带有小平面和颜色的 ggplot。颜色与 "ID" 相关,面的列与 "Type" 相关。一个 ID 总是在同一个 Type 中,但每个 Type 中有不同数量的 ID。我想重置每列刻面的颜色,以使颜色差异更大。

ggplot(data = plt_cont_em, aes(x = Jahr, y = Konz)) +
   geom_point(aes(color=factor(ID))) +
   facet_grid(Schadstoff_ID ~ Type, scales = "free_y")

现在看起来像:

我明白了,我必须为颜色引入一个虚拟变量。但是有没有一种简单的方法来计算每个类型中的 ID,在每个类型中从 1 开始?


由于数据是机密的,我创建了显示相同问题的虚拟数据。

     ID<-c()
     Type<-c()
     Jahr<-c()
     Schadstoff<-c()
     Monat<-c()
     Konz<-c()
    for (i in 1:25){
        #i = ID
        #t = Type
        t<-sample(c("A","B","C"),1)
        for (j in 1:5){
            #j = Schadstoff
            if(runif(1)<0.75){
                for(k in 2015:2020){
                    #k = Jahr
                    for(l in 1:12){
                        #l = Monat
                        if(runif(1)<0.9){
                             ID<-c( ID,i)
                             Type<-c( Type,t)
                             Jahr<-c( Jahr,k)
                             Schadstoff<-c( Schadstoff,j)
                             Monat<-c( Monat,l)
                             Konz<-c( Konz,runif(1))
                        }
                    }
                }
            }
        }
    }
    tmp<- data.frame(ID,Type, Jahr, Schadstoff, Monat, Konz)

tmp<-tmp %>% group_by( Type) %>% mutate( Color=row_number())

p<-ggplot(data = tmp, aes(x = Jahr, y = Konz)) +
    geom_point(aes(color=factor(Color)), size=0.8) +
    facet_grid(Schadstoff ~ Type, scales = "free") +
    theme_light() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
p

问题仍然存在,分组不起作用,每行的颜色都是唯一的。

使用 dplyr 您可以 group_by 键入并创建一个新列,其中包含每个组内 IDdense_rank

plt_cont_em %>%
  group_by(Type) %>%
  mutate(Type_ID = dense_rank()) %>%
  ggplot() + 
  ...

这将'rank'组内的每个ID从小到大,保留具有相同ID和相同值的记录。

然后您可能想要排除图例,因为它没有什么意义。

library(dplyr)
library(ggplot2)

# Using provided random data
tmp <- tmp %>% 
  group_by(Type) %>%
  mutate(Color = dense_rank(ID))

ggplot(data = tmp, aes(x = Jahr, y = Konz)) +
  geom_point(aes(color = factor(Color)), size = 0.8) +
  facet_grid(Schadstoff ~ Type, scales = "free") +
  theme_light() + 
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

reprex package (v0.3.0)

于 2020-04-02 创建