I have the following data frame which contains 4 columns of data in addition to the vector of labels c.
Time <-c(1:4) d<-data.frame(Time, x1= rpois(n = 4, lambda = 10), x2= runif(n = 4, min = 1, max = 10), x3= rpois(n = 4, lambda = 5), x4= runif(n = 4, min = 1, max = 5), c=c(1,1,2,3))
I would like to use ggpolt
to plot 4 curves"x1,..,x4"
above each others where each curve is colored according to the label. So curves x1
and x2
are colored by the same color since they have the same label where as curves x3
and x4
in different colors.
I did the following
d %>% pivot_longer(-c(Time,x1,x2,x3,x4))%>% rename(class=value) %>% select(-name) %>% pivot_longer(-c(Time,class)) %>% mutate(Label=ifelse(Time==max(Time,na.rm = T),name,NA), Label=ifelse(duplicated(Label),NA,Label)) %>% ggplot(aes(x=Time,y=value,color=factor(class),group=name))+ geom_line()+ labs(color='class')+ scale_color_manual(values=c('red','blue','green'))+ geom_label_repel(aes(label = Label), nudge_x = 1.5, na.rm = TRUE,show.legend = F,color='black')
but I don't get the needed plot, the resulted curves are not colored according to the label. I want x1
and x2
in red, x3
in blue and x4
in green.
To add: I would like to obtain the same plot above in the following general case, where I can't add the vector c
to the data frame as length(c)
is not equal to length(x1)=...=length(x4)
Time <-c(1:5) d<-data.frame(Time, x1= rpois(n = 5, lambda = 10), x2= runif(n = 5, min = 1, max = 10), x3= rpois(n = 5, lambda = 5), x4= runif(n = 5, min = 1, max = 5))
and c=c(1,1,2,3)
没有评论:
发表评论