r - 创建 ggplot2 中点的大小和颜色的渐变,超出现有值

标签 r ggplot2

我正在构建一个图,其中每个点的大小和颜色都基于两个单独列中的线性渐变

df1 <- data.frame (x = c(1:10), y = c(1:10), pointSize = 1:10, pointCol = 1:10)

ggplot(df1, aes(x = x, y = y, colour = pointCol, size = pointSize)) + geom_point() +
   scale_colour_gradient(low = "steelblue", high = "yellow")

表中编码颜色和点大小的列的最大值为 10。我可以更改渐变大小,使其从 say = 10 变为 20 吗?

最佳答案

您可以为两个图定义相同的尺寸比例限制。这是一个例子:

示例数据集:

df1 <- data.frame (x = 1:10, y = 1:10, pointSize = 1:10, pointCol = 1:10)
df2 <- data.frame (x = 1:10, y = 10:1, pointSize = 11:20, pointCol = 1:10)

未标准化尺寸比例的绘图(我们可以看到图 1 中的尺寸 10 与图 2 中的尺寸 20 匹配):

p1 <- ggplot(df1, aes(x = x, y = y, colour = pointCol, size = pointSize)) + 
  geom_point() +
  scale_colour_gradient(low = "steelblue", high = "yellow") +
  theme_bw()

p2 <- ggplot(df2, aes(x = x, y = y, colour = pointCol, size = pointSize)) + 
  geom_point() +
  scale_colour_gradient(low = "steelblue", high = "yellow") +
  theme_bw()

gridExtra::grid.arrange(p1, p2, nrow = 1)

plot1

现在让我们为两者定义相同的比例限制:

size.limits <- range(df1$pointSize, df2$pointSize)

> size.limits
[1]  1 20

将大小比例添加到每个图(我们现在可以看到这两个图共享相同大小的图例,并且图 1 中的最大点与图 2 中的最小点的大小相同):

gridExtra::grid.arrange(p1 + scale_size(limits = size.limits), 
                        p2 + scale_size(limits = size.limits), 
                        nrow = 1)

plot2

关于r - 创建 ggplot2 中点的大小和颜色的渐变,超出现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780229/

相关文章:

java - RJDBC、Java 连接到 Oracle 数据库崩溃

reshape 矩阵以获得网络

r - 使用 ggplot2 的分面点图中的因子顺序

r - 如何更改 Lollipop 行之间的距离

r - 添加图例条目使所有其他图例条目成为对角线和矩形

r - 如何定义自定义临时目录

通过对组内的列进行排序来重新排列数据框

R:将具有未知列类的 data.frame 中的字符转换为数字

r - ggplot2:在离散轴上显示每第 n 个值

R - ggplot geom_dotplot 形状选项