r - 如何将两种不同比例的颜色渐变与ggplot合并
问题描述
通过使用 R,是否可以将 2 个 ggplot 放在一起(即,在同一个图上)但具有不同的颜色渐变条?我的代码,例如,
library(ggplot2)
ggplot(df1, aes(duration, slopes, col = color)) +
geom_point(size = 3) +
scale_color_gradient(low = "black", high = "red")
ggplot(df2, aes(duration, slopes, col = color)) +
geom_point(size = 3) +
scale_color_gradient(low = "blue", high = "green")
产生以下两张图片
相反,我希望能够将它们集成在一个图中,一个红色和黑色的条形图和另一个蓝色和绿色的条形图。
解决方案
是的,如果您使用该ggnewscale
软件包,您可以:
a <- sample(nrow(iris), 75)
df1 <- iris[a,]
df2 <- iris[-a,]
library(ggnewscale)
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
geom_point(data = df1, aes(colour = Petal.Length)) +
scale_colour_gradientn(colours = c("red", "black")) +
# Important: define a colour/fill scale before calling a new_scale_* function
new_scale_colour() +
geom_point(data = df2, aes(colour = Petal.Width)) +
scale_colour_gradientn(colours = c("blue", "white"))
替代方案是中继器包,或来自ggh4xscale_colour_multi
的/ (完全免责声明:我写了 ggh4x)。scale_listed
编辑:以下是替代方案:
library(ggh4x)
# ggh4x scale_colour_multi (for gradientn-like scales)
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
geom_point(data = df1, aes(length = Petal.Length)) +
geom_point(data = df2, aes(width = Petal.Width)) +
scale_colour_multi(colours = list(c("red", "black"), c("blue", "white")),
aesthetics = c("length", "width"))
# ggh4x scale_listed (for any non-position scale (in theory))
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
geom_point(data = df1, aes(length = Petal.Length)) +
geom_point(data = df2, aes(width = Petal.Width)) +
scale_listed(list(
scale_colour_gradientn(colours = c("red", "black"), aesthetics = "length"),
scale_colour_gradientn(colours = c("blue", "white"), aesthetics = "width")
), replaces = c("colour", "colour"))
library(relayer)
# relayer
ggplot(mapping = aes(Sepal.Width, Sepal.Length)) +
rename_geom_aes(geom_point(data = df1, aes(length = Petal.Length)),
new_aes = c("colour" = "length")) +
rename_geom_aes(geom_point(data = df2, aes(width = Petal.Width)),
new_aes = c("colour" = "width")) +
scale_colour_gradientn(colours = c("red", "black"), aesthetics = "length",
guide = guide_colourbar(available_aes = "length")) +
scale_colour_gradientn(colours = c("blue", "white"), aesthetics = "width",
guide = guide_colourbar(available_aes = "width"))
所有替代方案都会对未知的美学提出警告,但这对于生成的情节无关紧要。产生这个警告的只是 ggplot 函数中的一行代码,如果不重新编码每个包装器,或者像 ggnewscale 所做的那样,重命名旧美学而不是提供新美学,layer()
就无法绕过这个问题。geom
这些情节看起来几乎相同,所以我想我不必再发布它们了。
推荐阅读
- javascript - 尝试在 HTML 中显示 API 数据
- sql - 如何对同一行中的列求和?
- python - 如何在不使用 pip 的情况下安装 pyqt5 和 pyqt5-tools?
- r - R 错误:“参数暗示不同的行数”——但经过检查,大小是相同的
- arrays - TCL列表数据转直方图
- flutter - 如何断言占位符文本在 Flutter 小部件测试中消失?
- javascript - 在分析 gtag 中获取 window.location.hostname
- openrefine - 如何添加减去两个现有列之间差异的列?OpenRefine 中的 GREL
- ios - Xcode 11 | 运行命令 Instruments -s devices | CoreData XRPackageModel 错误
- r - 如何为 diff() 设置单位?