r - creating 2 separate ggplots with same color scale
问题描述
library(raster)
library(ggplot2)
library(dplyr)
library(colorspace)
#I hope these are all the required packages, if not please let me know.
r1 <- raster(system.file("external/test.grd", package="raster"))
r2 <- r1^1.1
as.data.frame(r1, xy=TRUE) %>%drop_na() %>%
ggplot(aes(x=x, y=y)) +
geom_raster(aes(fill = test)) +
scale_fill_gradientn(
colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
breaks =c(505, 1100, 1600))
as.data.frame(r2, xy=TRUE) %>%drop_na() %>%
ggplot(aes(x=x, y=y)) +
geom_raster(aes(fill = test)) +
scale_fill_gradientn(
colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
breaks =c(505, 1100, 1600))
I have this example data. How can I make the 2 plots have the same colors for the same values & have the same defined breaks? The break numbers were just chosen arbitrarily. I want to have the plots separate.
I have found this link which tackles the exact problem but my data is different and I can't make it work. (it doesn't matter if some numbers are out of range)
what i tried so far:
rng = range(c((1900), (200)))
as.data.frame(r, xy=TRUE) %>%drop_na() %>%
ggplot(aes(x=x, y=y)) + geom_raster(aes(fill = test)) +
scale_fill_gradientn(colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
midpoint=mean(rng), breaks =seq(505, 1100, 1600),
limits=c(floor(rng[1]), ceiling(rng[2])))
Can anyone help me please with this problem?
解决方案
The problem is that you have reversed the fill scale with trans = "reverse"
, so the limits also need to be inverted:
as.data.frame(r1, xy=TRUE) %>%drop_na() %>%
ggplot(aes(x=x, y=y)) +
geom_raster(aes(fill = test)) +
scale_fill_gradientn(
colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
breaks =c(505, 1100, 1600), limits = c(2000, 0))
as.data.frame(r2, xy=TRUE) %>%drop_na() %>%
ggplot(aes(x=x, y=y)) +
geom_raster(aes(fill = test)) +
scale_fill_gradientn(
colours = hcl.colors(10, "YlGnBu"),trans = "reverse",
breaks =c(505, 1100, 1600), limits = c(2000, 0))
推荐阅读
- javascript - 在浏览器搜索中显示引导模式链接
- kubernetes - 是否可以为虚拟服务中的路由目的地设置后备?
- python - 通过源使用 reticulate 时没有名为“rpytools”的模块
- google-slides-api - 如何通过 Slides API 更改 Google 幻灯片演示主题?
- javascript - 在同一个项目中加载多个 jquery 版本但不同的页面
- c# - C# - 通用方法不能使用对象的字段
- android - 为什么我发布的游戏的分辨率低于原始版本?
- eclipse - 线程“AWT-EventQueue-0”中的异常 java.lang.NullPointerException:无法调用“java.net.URL.toExternalForm()”,因为“位置”为空
- angular - 物料表 - 无法正确实施
- vba - VBA Microsoft Project Professional 2016:如何按日期按资源按任务阅读实际时间和工作(小时)?