繁体   English   中英

情节中使用的美学尺度| ggplot2

[英]Scale for aesthetics used in the plot | ggplot2

我是ggplot2的绝对初学者。 我对ggplot2感到沮丧,并开始阅读Wickham的那本很棒的书。 他说,“ 情节上使用的每种美学都需要一个比例尺。

因此,我做了以下工作:

尝试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."

我对此进行了谷歌搜索,并在SO上找到了以下线程: ggplot2错误:手动刻度中的值不足 在原始帖子中,为什么他/她添加了额外的颜色是合理的。 但是,我不确定为什么在我的示例中会是这种情况,因为我有两层,每层都有自己的美感。

试试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")) 

令人惊讶的是,上面的代码显示了一些奇怪的东西-我有两种美感,只有一种尺度。

问题1:这非常令人惊讶,因为我们可以看到有两个几何,但是只有一个比例。 正确? 我知道威克汉姆不会错。 那么,我想念什么?

问题2:此外,出于好奇,如果我有多个几何图形,每个几何图形都具有上述一种美感,并且每个图形都有一个比例尺,ggplot将如何知道哪个比例尺与哪个几何图形相关联? 就像in一样,ggplot2如何知道layer1是否与color = red比例一致而layer2与color = blue比例一致?

衷心感谢您的想法。 提前致谢。


要回答评论中的特定问题:

如果要强制使用特定颜色,则需要使用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")))

结果图

但是,对于线型,我会使用其他外观。

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

第二个结果图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM