首页 文章

用于绘图的美学尺度| GGPLOT2

提问于
浏览
0

我是ggplot2的绝对初学者 . 我对ggplot2感到沮丧,并开始阅读Wickham的精彩书籍 . 他说“在剧情中使用的每一种美学都需要一个尺度 . ”

所以,我做了以下事情:

Try 1:

huron <- data.frame(year = 1875:1972, level = as.numeric(LakeHuron))
   ggplot(huron, aes(year)) +
     geom_line(aes(y = level + 5, color = "y+5")) +
     scale_color_manual(values = c("orange")) +
     geom_line(aes(y = level - 5, color = "y-5")) +
     scale_color_manual(values = "blue")

运行此操作后,我收到错误提示 " insufficient value of colors provided."

我用Google搜索并在SO上找到了以下主题:ggplot2 Error: Insufficient values in manual scale . 在原帖中,为什么他/她添加额外的颜色是有道理的 . 但是,我不确定为什么在我的例子中会出现这种情况,因为我有两层,每层都有自己的美学 .

Try 2

这段代码可以工作:(因为我可以看到两种不同颜色的两个线图和一个图例 - 这是我的目标)

ggplot(huron, aes(year)) +
     geom_line(aes(y = level + 5, color = "y+5")) +
     scale_color_manual(values = c("orange", "blue")) + #Added another color here.
     geom_line(aes(y = level - 5, color = "y-5"))

令人惊讶的是,上面的代码显示了一些奇怪的东西 - 我有两个美学,只有一个规模 .

Question 1: 这是相当令人惊讶的,因为我们可以看到有两个geom但只有一个比例 . 正确?我知道威克姆不能错 . 那么,我错过了什么?

Question 2: 另外,出于好奇,如果我有多个geoms,每个都有一个美学,如上例所示,并且每个都有一个比例,ggplot将如何知道哪个比例与哪个geom相关联?如同,ggplot2将如何知道layer1是否与 color = red 的比例一致,而layer2与 color = blue 一起使用?

我真诚地感谢你的想法 . 提前致谢 .


1 回答

  • 2

    要回答评论中的具体问题:

    如果要强制使用特定颜色,则需要使用 scale_color_manual . 顾名思义,这需要一些手工工作 .

    library(ggplot2)
    
    #default colors
    #http://stackoverflow.com/a/8197703/1412059
    gg_color_hue <- function(n) {
      hues = seq(15, 375, length = n + 1)
      hcl(h = hues, l = 65, c = 100)[1:n]
    }
    
    ggplot(mpg, aes(displ, hwy)) + 
      geom_point(aes(colour = class)) + 
      geom_smooth(method = "lm", se = FALSE, aes(color = "model")) +
      scale_color_manual(values = setNames(c(gg_color_hue(length(unique(mpg$class))), "red"),
                                           c(unique(mpg$class), "model")))
    

    resulting plot

    但是,我会对线型使用额外的美学 .

    ggplot(mpg, aes(displ, hwy)) + 
      geom_point(aes(colour = class)) + 
      geom_smooth(method = "lm", se = FALSE, aes(linetype = "model"), color = "red")
    

    second resulting plot

相关问题