【发布时间】:2020-07-14 10:37:12
【问题描述】:
我有一个带有刻面和颜色的 ggplot。颜色与“ID”相关,构面的列与“类型”相关。一个 ID 始终属于同一类型,但每个类型中有不同数量的 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
问题仍然存在,分组不起作用并且每行的颜色都是唯一的。
【问题讨论】:
标签: r ggplot2 dplyr colors facet