【问题标题】:Overlaying two geom_bin2d plots with two different color scale用两种不同的色标覆盖两个 geom_bin2d 图
【发布时间】:2018-10-17 15:51:51
【问题描述】:

我找不到如何为传递给 geom_bin2d 的两个不同数据集正确指定两个色阶。

下面的代码不起作用,第一个“scale_fill_gradient”调用被忽略,在抛出以下错误消息后只使用最后一个(白色到蓝色):

“填充”比例已存在。为“填充”添加另一个比例,它将替换现有比例。

这里有一个最少的代码:

require(ggplot2)
dfA <- data.frame(x=rnorm(50000, mean=5),  y=rnorm(50000, mean=5))
dfB <- data.frame(x=rnorm(30000, mean=25), y=rnorm(30000, mean=25))

ggplot() + theme_bw() + 
  geom_bin2d(data=dfA, aes(x=x, y=y), bins=100) +
  scale_fill_gradient(low="white", high="red") + 
  geom_bin2d(data=dfB, aes(x=x, y=y), bins=100) + 
  scale_fill_gradient(low="white", high="blue")

这是结果图:

有没有办法指定两种不同的颜色比例,以便来自 dfA 和来自 dfB 的点具有两种不同的颜色渐变?

谢谢

【问题讨论】:

    标签: r ggplot2 colors


    【解决方案1】:

    您可以先创建两个单独的图,然后为每个图获取基础计算数据并将它们组合起来:

    # create separate plots
    p1 <- ggplot() + theme_bw() +
      geom_bin2d(data=dfA, aes(x=x, y=y), bins=100) +
      scale_fill_gradient(low="white", high="red")
    
    p2 <- ggplot() + theme_bw() +
      geom_bin2d(data=dfB, aes(x=x, y=y), bins=100) + 
      scale_fill_gradient(low="white", high="blue")
    
    # combined plot using layer_data() to extract data
    # from each plot above, & scale_identity to use the
    # already calculated fill values
    p.combined <- ggplot(data = layer_data(p1),
           aes(x = x, y = y, fill = fill)) +
      geom_tile() +
      geom_tile(data = layer_data(p2)) +
      scale_fill_identity() +
      theme_bw()
    
    # optional: add legends to the combined plot
    library(cowplot)
    plot_grid(p.combined,
              plot_grid(get_legend(p2),
                        get_legend(p1),
                        ncol = 1),
              nrow = 1,
              rel_widths = c(1, 0.1)) # optimal relative widths may change, depending on plot dimensions
    

    【讨论】:

    • 您好 Z.Lin,非常感谢您的回复。这几乎是我想要的。是否可以强制两个比例具有相同的范围?在我的图中,对应于 dfA 数据的点比来自 dfB 的点更暗,因为计数更高(我故意生成了不同大小的 dfA 和 dfB)。相反,在您的解决方案中,最深的红色和最深的蓝色对应于两个不同的计数(红色刻度中超过 60 个计数和超过 40 个计数),而我更希望有两个色标但具有相同的 min .. max范围。
    【解决方案2】:

    好的,我发现我可以通过将选项 limits=c(min, max) 传递给 @Z.Lin 答案中的 scale_fill_gradient 函数来解决我的问题。

    【讨论】:

    • 将正确答案打勾授予您自己的消息而不是授予 Z.Lin 并不是很好。无礼。
    猜你喜欢
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多