在`ggplot2`中使用多个`scale_fill_`

ros*_*ova 9 r ggplot2

我正在尝试显示多个图层ggplot2,但我想scale_fill_为每个图层使用不同的颜色方案.我似乎无法做到这一点,因为调用scale_fill_gradientn两次的东西只会用第二次调用覆盖第一次调用.

library( ggplot2 )
library( reshape2 )
library( RColorBrewer )
set.seed( 123 )
Run Code Online (Sandbox Code Playgroud)

我将首先绘制一个tile网格(注意我正在设置颜色scale_fill_gradientn):

foo <- matrix( data = rnorm( 100 ), ncol = 10 )
foo <- melt( foo )

plot <- ggplot() +
  geom_tile( data = foo,
             mapping = aes( x = Var1, y = Var2, fill = value ) ) +
  scale_fill_gradientn(
    colours = rev( brewer.pal( 7, "BrBG" ) )
  )
plot
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在我想在那个上面添加另一个情节,但是有一个独特的配色方案.我可以创建一个不同的情节:

bar <- data.frame( x = rnorm( 100, 4, 1 ),
                   y = rnorm( 100, 6, 1.5 ) )

ggplot() +
  stat_density_2d( data = bar,
                   mapping = aes( x = x, y = y, fill = ..level.. ),
                   geom = "polygon" ) +
  scale_fill_gradientn(
    colours = rev( brewer.pal( 7, "Spectral" ) )
  ) + xlim( 0, 10 ) + ylim( 0, 10 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想要做的是将第二个绘图绘制在第一个绘图的顶部,但保留您在上面看到的颜色方案.如果我尝试简单地在第一层的顶部添加第二层,我会覆盖原始scale_fill_gradientn图层,并强制两个图层共享一个颜色方案(在这种情况下,"压缩"第二层完全落在一种颜色中:

plot <- plot +
  stat_density_2d( data = bar,
                   mapping = aes( x = x, y = y, fill = ..level.. ),
                   geom = "polygon" ) +
  scale_fill_gradientn(
    colours = rev( brewer.pal( 7, "Spectral" ) )
  ) + xlim( 0, 10 ) + ylim( 0, 10 )
plot
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

有没有办法为每一层指定单独的颜色方案?我注意到,例如,stat_density_2d理解colour美学,但我尝试指定一个无济于事(它只在图例中添加颜色作为标签,并将颜色方案恢复为默认值):

ggplot() +
  stat_density_2d( data = bar,
                   mapping = aes( x = x, y = y, fill = ..level.., colour = "red" ),
                   geom = "polygon" ) +
  xlim( 0, 10 ) + ylim( 0, 10 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我觉得必须有一种不同的方式来设置"每层"的颜色方案,但我显然在错误的地方寻找.

Axe*_*man 10

绕过限制的一种方法是改为映射到颜色(正如您已经暗示的那样).这是如何:

我们保留基础栅格图,然后添加:

plot +
  stat_density_2d( data = bar,
                   mapping = aes( x = x, y = y, col = ..level.. ),
                   geom = "path", size = 2 ) +
  scale_color_gradientn(
    colours = rev( brewer.pal( 7, "Spectral" ) )
  ) + xlim( 0, 10 ) + ylim( 0, 10 )
Run Code Online (Sandbox Code Playgroud)

这给了我们:

在此输入图像描述

这并不完全令人满意,主要是因为这些尺度具有相当多的感知重叠(我认为).玩不同的尺度肯定会给我们带来更好的结果:

plot <- ggplot() +
  geom_tile( data = foo,
             mapping = aes( x = Var1, y = Var2, fill = value ) ) +
  viridis::scale_fill_viridis(option = 'A', end = 0.9)

plot +
  stat_density_2d( data = bar,
                   mapping = aes( x = x, y = y, col = ..level.. ),
                   geom = "path", size = 2 ) +
  viridis::scale_color_viridis(option = 'D', begin = 0.3) + 
  xlim( 0, 10 ) + ylim( 0, 10 )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在我看来仍然不是很好(使用多个色标让我感到困惑),但更容易忍受.


小智 6

看起来ggnewscale最近被开发为允许在单个绘图中使用多个比例 - 特别是颜色和填充比例。