ggplot 散点图,随着值变小而变大的点。一定范围内的值应该都具有相同的大小

ggplot scatterplot, dots that get larger as values become smaller. Values within certain range should all have the same size

让我给你看我的部分数据:

df <- structure(list(No = 1:9, X = c(0.005, 0.011, 0.011, 0.011, 0.011, 
0.016, 0.023, 0.022, 0.029), Y = c(0.457, 0.166, 0.208, 0.212, 
0.226, 0.107, 0.029, 0.055, 0.026)), class = "data.frame", row.names = c(NA, 
-9L))

我现在正在寻找一个散点图,它在 x 轴上显示 'No',在 y 轴上显示 X 值。图中显示的点应该随着 Y 值变小而增加。具体来说,我希望一定范围内的点都具有相同的大小:

    range     | size
_____________________
    1 - 0.15  |   1
0.149 - 0.10  |   3
 0.09 - 0.05  |   5
0.049 - 0.01  |   9
0.009 - 0     |   11 

我在 R 中已有以下代码,它完成了大部分工作:

plot <- ggplot(df, aes(x=No, y=X)) + 
  geom_point(aes(colour = Y, size = Y)) +
  scale_colour_continuous(low = "darkblue", high = "grey", 
                      breaks = c(1, 0.15, 0.1, 0.05, 0.01)) +
  labs(y = "Y-axis", x = "X-axis", size = "Determined by Y", colour = "Determined by Y")

legend_size <- c(3, 5, 9)
plot <- plot + scale_size(range = c(11,1), breaks = c(1, 0.15, 0.1, 0.05, 0.01)) + 
  guides(
    color = guide_legend(),
    size = guide_legend(override.aes = list(size = legend_size))) 

这是结果图:

我不喜欢的情节是它似乎并不准确。例如。第二个点看起来是 3 号的,而它应该是 1 号的(就像第一个点一样)。 (如果我在 'legend size' 中指定更多尺寸,我会收到一条错误消息。) 如果有人能告诉我如何为每个范围设置不同的颜色,那也会非常有帮助。

非常感谢您的帮助!

为了 size 反映值的范围,您必须使变量离散。为此,我根据您想要的尺寸根据您的范围和标签使用 cut 来离散化 Y。为了在绘图中使用这个新变量,我将其转换为具有根据点大小值的数值。

这个新变量映射到 size 上,我使用 scale_size_identity 自动给出正确的尺寸。

至于颜色,我使用了我使用 colorRampPalette 构建的离散调色板。为了获得绘图中的颜色,我使用 scale_color_manual。最后,要为尺寸和颜色获得一个图例,重要的是要为尺寸和颜色标度设置相同的断点、标签、限制……。

# Sizes and Labels
sizes <- c(1, 3, 5, 9, 11)
labels = c(0.01, 0.05, 0.1, 0.15, 1)

library(dplyr)
library(ggplot2)

# Make Y discrete
df1 <- df %>% 
  dplyr::mutate(df,Y1 = cut(Y, right = FALSE, breaks = c(0, labels), labels = rev(sizes)),
         Y1 = as.numeric(as.character(Y1)))

# Color Palette
cols <- colorRampPalette(c("darkblue", "grey"))(5)
cols <- setNames(cols, sizes)
cols
#>         1         3         5         9        11 
#> "#00008B" "#2F2F97" "#5F5FA4" "#8E8EB1" "#BEBEBE"

ggplot(df1, aes(x=No, y = X)) + 
  geom_point(aes(color = factor(Y1), size = Y1)) +
  scale_color_manual(breaks = sizes, 
                     labels = labels, 
                     values = cols, 
                     limits = factor(sizes)) +
  scale_size_identity(breaks = sizes, 
                      labels = labels, 
                      limits = range(sizes),
                      guide = "legend") +
  labs(y = "Y-axis", x = "X-axis", size = "Determined by Y", colour = "Determined by Y")

reprex package (v0.3.0)

于 2020-06-28 创建