ggplot2 plot table as lines

后端 未结 3 1201
孤街浪徒
孤街浪徒 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:21

    The trick is to reshape your data into tall format before you pass it to ggplot. This is easy when using the melt function in package reshape2:

    Assuming your data is a variable called df:

    library(reshape2)
    library(ggplot2)
    
    mdf <- melt(df, id.vars="X")
    str(mdf)
    ggplot(mdf, aes(x=variable, y=value, colour=X, group=X)) + geom_line() +
        opts(axis.text.x = theme_text(angle=90, hjust=1))
    

    enter image description here


    Edit As @Chase suggests, you can use facetting to make the plot more readable:

    ggplot(mdf, aes(x=X, y=value)) + geom_point() +
        opts(axis.text.x = theme_text(angle=90, hjust=1)) + facet_wrap(~variable)
    

    enter image description here

提交回复
热议问题