gpt4 book ai didi

r - 分别编辑 2 stat_hex_bin geoms ggplot2

转载 作者:行者123 更新时间:2023-12-04 12:09:40 24 4
gpt4 key购买 nike

我首先给你我的示例代码:

x <- runif(1000,0, 5)
y <- c(runif(500, 0, 2), runif(500, 3,5))
A <- data.frame("X"=x,"Y"=y[1:500])
B <- data.frame("X"=x,"Y"=y[501:1000])
ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10) +
scale_fill_continuous(low="red4", high="#ED1A3A")

它产生以下情节:
enter image description here

现在我希望较低的六边形遵循不同的比例。即从深绿色到浅绿色。我怎样才能做到这一点?

更新:
从目前的答案中可以看出,我在问自己是否有不使用 alpha 比例的解决方案。此外,使用没有边距或类似内容的两个图对于我的特定应用程序来说不是一种选择。虽然他们都是合法的答案:)

最佳答案

与其尝试在一个图中获得两种不同的填充比例,您还可以在图构建后更改较低值的颜色。基本思想是有两个具有不同填充比例的图,然后将某些细节从一个图复制到另一个图。

# Base plot
p <- ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10)

# Produce two plots with different fill colours
p1 <- p + scale_fill_continuous(low="red4", high="#ED1A3A")
p2 <- p + scale_fill_continuous(low="darkgreen", high="lightgreen")

# Get fill colours for second plot and overwrite the corresponding
# values in the first plot
g1 <- ggplot_build(p1)
g2 <- ggplot_build(p2)
g1$data[[1]][,"fill"] <- g2$data[[1]][,"fill"]

# You can draw this now but there is only one legend
grid.draw(ggplot_gtable(g1))

要拥有两个传说,您可以将两个情节中的传说连接在一起
# Bind the legends from the two plots together
g1 <- ggplot_gtable(g1)
g2 <- ggplot_gtable(g2)

g1$grobs[[grep("guide", g1$layout$name )]] <-
rbind(g1$grobs[[grep("guide", g1$layout$name )]],
g2$grobs[[grep("guide", g2$layout$name )]] )

grid.newpage()
grid.draw(g1)

给予(来自 set.seed(10) 数据生成之前)

enter image description here

关于r - 分别编辑 2 stat_hex_bin geoms ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34679260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com