Specific Variable Color in ggplot

后端 未结 2 793
无人共我
无人共我 2021-01-24 01:32

Let\'s say I have the following data set:

set.seed(1)
df <- data.frame(
  Index = 1:10,
  Heat = rnorm(10),
  Cool = rnorm(10),
  Other = rnorm(10),
  a = rno         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 01:52

    Mixing your own colors in with a default color palette is a breathtakingly bad idea. Nevertheless, here is one way to do it - similar to the other answer but perhaps a bit more general, and uses ggplot's default color palette for everything else as you asked.

    library(ggplot2)
    library(reshape2)
    gg.df <- melt(df, id="Index", value.name="Component")
    ggp <- ggplot(gg.df, aes(x = Index, y = Component, color = variable)) +
      geom_line()
    
    lvls  <- levels(gg.df$variable)
    cols  <- setNames(hcl(h=seq(15, 375, length=length(lvls)+1), l=65, c=100),lvls)
    cols[c("Heat","Cool","Other")] <- c("#FF0000","#0000FF","#00FF00")
    
    ggp + scale_color_manual(values=cols)
    

    Edit: Just realized that I never said why this is a bad idea. This post gets into it a bit, and has a few really good references. The main point is that the default colors are chosen for a very good reason, not just to make the plot "look pretty". So you really shouldn't mess with them unless there's an overwhelming need.

提交回复
热议问题