首页 文章

ggplot2:通过颜色和线型区分线条

提问于
浏览
1

因此,当我必须绘制很多线时,我可以通过颜色或线型来区分它们

library(ggplot2)
pd = cbind.data.frame(x = rep(c(1,2), each = 4), 
              y = rep(1:4, times=2), 
              type = rep(c("A", "B", "C", "D"), times=2))
ggplot(pd, aes(x=x, y=y, col=type)) + geom_line() + theme_bw()
ggplot(pd, aes(x=x, y=y, lty=type)) + geom_line() + theme_bw()

赠送:

enter image description here

enter image description here

但我想要两者并且我想要自动选择颜色和线型(即我不想为每个 type 手动指定颜色和线型,如此问题:ggplot2 manually specifying color & linetype - duplicate legend) .

以下是我所需输出的示例(加上自动生成的图例):

enter image description here

理想的是命令就像

ggplot(pd, aes(x=x, y=y, style=type)) + geom_line() + theme_bw()

但我想需要一个解决方法 .

P.S:这样做的动机是20行很难通过颜色或线型来区分,这就是为什么我在寻找两者的组合 . 因此,红色虚线与实心红线不同,两者都与实心蓝线不同 . 每次我将数据提供给ggplot时,我都不想自己指定和选择颜色和线型 .

2 回答

  • 0

    我知道你想要避免手动规范,但它不必像你链接的例子那样令人生畏 . 以下示例为20行( color_lty_cross 最多可容纳60行):

    library(ggplot2)
    
    pd = cbind.data.frame(x = rep(c(1,2), each = 20), 
                          y = rep(1:20, times=2), 
                          type = rep(LETTERS[1:20], times=2))
    
    # this function regenerates ggplot2 default colors
    gg_color_hue <- function(n) {
      hues = seq(15, 375, length = n + 1)
      hcl(h = hues, l = 65, c = 100)[1:n]
    }
    
    color_lty_cross = expand.grid(
      ltypes = 1:6,
      colors = gg_color_hue(10)
      ,stringsAsFactors = F)
    
    
    ggplot(pd, aes(x=x, y=y, col=type, lty = type)) + 
      geom_line() + 
      scale_color_manual(values = color_lty_cross$colors[1:20]) +
      scale_linetype_manual(values = color_lty_cross$ltypes[1:20]) +
      theme_bw()
    

    您可以使用合并快速映射到 type 您可以使用更简单的颜色然后 gg_color_hue 映射ggplot2默认值 .

    enter image description here

  • 1

    您还可以通过三角形或圆形等几何图形来区分线条 . 如果您的数据很少(例如100个样本),您只需在绘图属性中选择type =“b”,但如果您有大量数据(如1万个样本),则可以在生成的线上绘制几何图形,以便您可以使用points()命令将其间隔开来,您可以在其中指定点的x和y坐标 . 否则数字将相互重叠 . 示例(带代码):

    enter image description here

    #!/usr/bin/Rscript
    
    args = commandArgs(trailingOnly=TRUE)
    dataLocation = args[1]
    fileName = args[2]
    abs_path = args[3]
    
    myData <- read.csv(dataLocation, sep = ";")
    
    #paste0 concatenates two strings
    fullFileName = paste0(abs_path,fileName)
    
    #plot first line
    
    png(fullFileName, width = 1300, height = 600)
    
    plot(myData[,1], type = "l", cex = 2, cex.axis = 3.0, lty = 1 ,cex.lab = 3.0, ylim = c(0, max(myData)), xlab = "Iteração", ylab = "Valor")
    
    limit = ncol(myData)
    
    if(limit > 1){
    
        for (column in 2:limit){
            lines(myData[,column], lty = 1, type = "l")
        }
    }
    
    for(i in 1:500){
    
       if(i %% 100 == 0){
    
          points(i, myData[i,1], pch = 16, cex = 1.5)
          points(i, myData[i,2], pch = 24, cex = 1.5)
          points(i, myData[i,3], pch = 0, cex = 1.5)
          points(i, myData[i,4], pch = 15, cex = 1.5)
    
       }
    
    }
    
    dev.off()
    

相关问题