How to plot multiple lines in R

前端 未结 2 1506
夕颜
夕颜 2021-01-11 15:59

I have a data that looks like this:

#d  TRUE    FALSE   Cutoff
4   28198   0   0.1
4   28198   0   0.2
4   28198   0   0.3
4   28198   13  0.4
4   28251   61         


        
相关标签:
2条回答
  • 2021-01-11 16:24

    Here's a base R method, assuming your data is called dat in this example:

    plot(1:max(dat$false), xlim = c(0,611),ylim =c(19000,28251), type="n")
    
    apply(
    rbind(unique(dat$d),1:2),
    #the 1:2 here are your chosen colours
    2,
    function(x) lines(dat$false[dat$d==x[1]],dat$true[dat$d==x[1]],col=x[2])
    )
    

    Result:

    enter image description here

    edit - while using lowercase true/false for variable names is accepted, it probably still isn't the greatest coding practice.

    0 讨论(0)
  • 2021-01-11 16:44

    Since your data is already in long format and I like ggplot graphics anyway, I'd suggest that path. After reading your data in (note that TRUE and FALSE are not valid names, so R appended a . to the column names), the following should work:

    require(ggplot2)
    ggplot(dat, aes(FALSE., TRUE., colour = as.factor(d), group = as.factor(d))) + 
      geom_line()
    

    The ggplot2 website is full of good tips. Also note this search query on SO for lots of other good tips on related topics.

    enter image description here

    And for the record, here's how I'd approach your problem modifying your original code:

    colnames(dat)[2:3] <- c("T", "F")
    
    dis <- unique(dat$d)
    
    plot(NA, xlim = c(0, max(dat$F)), ylim = c(0, max(dat$T)))
    for (i in seq_along(dis)){
      subdat <- subset(dat, d == dis[i])
      with(subdat, lines(F,T, col = linecols[i]))
    }
    legend("bottomright", legend=dis, fill=linecols)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题