Reputation: 59
I have a ggplot with facets and colors. The colors are related to "ID" and the columns of the facets are related to "Type". One ID is always in the same Type but there are a different numbers of IDs in each Type. I would like to reset the colors with each column of the facets to have a bigger difference in the colors.
ggplot(data = plt_cont_em, aes(x = Jahr, y = Konz)) +
geom_point(aes(color=factor(ID))) +
facet_grid(Schadstoff_ID ~ Type, scales = "free_y")
Now it looks like:
I understand, that I have to introduce a dummy var for the color. But is there an easy way of numerating the IDs in each Type, starting in each Type with 1?
Since the data is confidential, I created dummy data that shows the same problem.
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
Problem still exists, that the grouping doesn't work and Color is unique for each line.
Upvotes: 4
Views: 341
Reputation: 13680
Using dplyr
you can group_by
Type and create a new column with the dense_rank
of the ID
inside each group:
plt_cont_em %>%
group_by(Type) %>%
mutate(Type_ID = dense_rank()) %>%
ggplot() +
...
This will 'rank' each ID from smallest to biggest inside the group, keeping records with the same ID with the same value.
You will probabily then want to exclude the legend, as it'll have little sense.
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))
Created on 2020-04-02 by the reprex package (v0.3.0)
Upvotes: 1