0

我正在尝试根据值是正值还是负值来xend为我的哑铃图中的点着色。x_diff本质上,如果x_diff值为正,我希望xend点为绿色,如果为负,则为红色。我试图在我的数据中定义它,但是当我尝试通过ggplot我现在编写的代码的方式运行它时,我遇到了困难。有没有人有任何可能有帮助的建议?示例代码如下。

谢谢你。

library(tidyverse)
library(ggalt)

data <- tibble(
  id = c(paste0("player", 1:5)),
  x1 = c(0.219, 0.169, 0.103, 0.193, 0.345),
  x2 = c(0.258, -0.030, 0.071, 0.315, 0.223),
  x_diff = x2 - x1,
  point_colour = ifelse(x_diff > 0, "#046A38", "#C60C30")
)

plot <- data %>%
  ggplot() +
  geom_dumbbell(aes(x = x1, xend = x2, y = id), size = 2, colour = "#E3E2E1",
                size_x = 4, size_xend = 4, colour_xend = data$x_diff) +
  theme_classic()
  
plot
4

1 回答 1

1

可能不是最优雅的解决方案,但您可以重叠geom_point(),并根据需要为其着色:

 data %>%
 ggplot() +
 geom_dumbbell(aes(x = x1, xend = x2, y = id),
               size = 2, colour = "#E3E2E1",size_x = 4, size_xend = 4) +
  geom_point(aes(x = x2, y = id), color = data$point_colour, size = 4) +
  theme_classic()

在此处输入图像描述

于 2021-08-16T06:56:28.783 回答