如何在不同的几何图形中具有相同的美学(颜色),不同的比例?

问题描述 投票:0回答:1

此代码显然不起作用(它对两个分类变量使用相同的图例和颜色方案。

require(ggplot2)

dt <- ggplot2::diamonds ; dt <- dt [1:20,];dt 
ggplot(dt) + 
  geom_point(aes(depth,carat, col=cut)) + 
  geom_point(aes(depth,carat, col=clarity)) +
  scale_colour_brewer("greens", name="cut") +  
  scale_colour_brewer("Reds", name="cut") +
  guides(colour= guide_legend("CUT")) + 
  guides(colour = guide_legend("CLARITY"))

绘制此图的正确方法是什么?

r ggplot2
1个回答
3
投票

没有正确的方法来执行此操作。不能以这种方式使用Ggplot,因为您试图将两个变量映射到相同的比例。但是,您可以通过劫持填充比例来为您完成这项工作,从而在某种程度上避免ggplot的局限性:

ggplot(dt) +
  geom_point(aes(depth, carat, fill = cut), shape = 21, colour = "transparent") +
  geom_point(aes(depth, carat, colour = clarity)) +
  scale_colour_brewer(palette = "Greens", name = "cut") +
  scale_fill_brewer(palette = "Reds", name = "clarity")

enter image description here

诀窍是使用具有填充的形状,并使用该填充来映射变量。不利的一面是,这个技巧不能扩展到任何数量的变量。有一些可以实现所需功能的程序包,即ggnewscalerelayer

带有ggnewscale软件包的示例:

library(ggnewscale)

ggplot(dt) +
  geom_point(aes(depth, carat, colour = cut)) +
  scale_colour_brewer(palette = "Greens", name = "cut") +
  new_scale_color() +
  geom_point(aes(depth, carat, colour = clarity)) +
  scale_colour_brewer(palette = "Reds", name = "clarity")

enter image description here

对于中继器型号:

library(relayer)

ggplot(dt) +
  rename_geom_aes(geom_point(aes(depth, carat, cut = cut)), new_aes = c("colour" = "cut")) +
  rename_geom_aes(geom_point(aes(depth, carat, clarity = clarity)), new_aes = c("colour" = "clarity")) +
  scale_colour_brewer(palette = "Greens", aesthetics = "cut") +
  scale_colour_brewer(palette = "Reds", aesthetics = "clarity")
Warning: Ignoring unknown aesthetics: cut
Warning: Ignoring unknown aesthetics: clarity

enter image description here

希望这有所帮助!

编辑:显然,在上面的图上,点上仅显示一种颜色,因为您在同一图样上重叠了相同的x和y坐标。我觉得我需要指出这一点。

© www.soinside.com 2019 - 2024. All rights reserved.