ggplot2 plot table as lines

后端 未结 3 1217
孤街浪徒
孤街浪徒 2021-02-04 16:47

I would like to plot the following dataset

structure(list(X = structure(c(3L, 12L, 11L, 7L, 13L, 2L, 1L, 
10L, 5L, 4L, 8L, 14L, 9L, 6L), .Label = c(\"BUM\", \"DD         


        
3条回答
  •  庸人自扰
    2021-02-04 17:06

    This is an extension to @Andrie's solution. It combines the faceting idea with that of overplotting (stolen liberally from the learnr blog, which I find results in a cool visualization. Here is the code and the resulting output. Comments are welcome

    mdf <- melt(df, id.vars="X")
    mdf = transform(mdf, variable = reorder(variable, value, mean), Y = X)
    
    ggplot(mdf, aes(x = variable, y = value)) + 
      geom_line(data = transform(mdf, X = NULL), aes(group = Y), colour = "grey80") +
      geom_line(aes(group = X)) +
      facet_wrap(~X) +
      opts(axis.text.x = theme_text(angle=90, hjust=1))
    

    enter image description here

    EDIT: If you have groupings of milieus, then a better way to present might be the following

    mycols = c(brewer.pal(4, 'Oranges'), brewer.pal(4, 'Greens'), 
               brewer.pal(3, 'Blues'), brewer.pal(3, 'PuRd'))
    mdf2 = read.table(textConnection("
      V1,  V2
      ETB, LEIT
      PMA, LEIT
      PER, LEIT
      LEIT, LEIT
      KON, TRADITION
      TRA, TRADITION
      DDR, TRADITION
      TRADITION, TRADITION
      BUM, MAIN
      MAT, MAIN
      MAIN, MAIN
      EXP, HEDOS
      HED, HEDOS
      HEDOS, HEDOS"), sep = ",", header = T, stringsAsFactors = F)
    
    mdf2 = data.frame(mdf2, mycols = mycols)
    mdf3 = merge(mdf, mdf2, by.x = 'X', by.y = "V1")
    
    p1 = ggplot(mdf3, aes(x = variable, y = value, group = X, colour = mycols)) + 
      geom_line(subset = .(nchar(as.character(X)) == 3)) +
      geom_line(subset = .(nchar(as.character(X)) != 3), size = 1.5) +
      facet_wrap(~ V2) +
      scale_color_identity(name = 'Milieus', breaks = mdf2$mycols, labels = mdf2$V1) +
      theme_bw() + 
      opts(axis.text.x = theme_text(angle=90, hjust=1)) 
    

    enter image description here

提交回复
热议问题