scale_color_gradient无法正常使用ggplot

p4rjhz4m  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在尝试做一些类似于Baseball Savant上的百分位数排名的东西,但我不能让颜色变化工作。目前,ggplot正确地排名打者的基础上,他们的最大出口速度,但点的颜色总是得到卡住的“中间”的颜色,无论点的位置。

test_df <- data.frame(
  Batter = c("Player 1", "Player 2", "Player 3", "Player 4"),
  MaxExitVelo = c(105, 107, 102, 108),
  rank = c(1, 2, 3, 4)
)
test_df %>% 
  filter(Batter == "Player 2") %>% #Manually change Batter name to calculate ranking
  ggplot(aes(x = rank, y = "")) +
  geom_point(size = 10, aes(color = rank)) +
  geom_text(aes(label = rank)) +
  geom_label(aes(label = round(MaxExitVelo, digits = 1)), nudge_x = 0, nudge_y = 0.15) +
  ggtitle("Max Exit Velocity") +
  scale_x_reverse(expand = c(0,0.5), limits = c(max_rank + 1,  0)) +
  scale_color_gradient2(low = "blue", mid = "white", high = "red") + 
  theme_linedraw(base_line_size = 5) +
  theme(legend.position = "none",
         panel.border = element_rect(color = "white"),
         panel.grid.major.x = element_blank(),
         panel.grid.minor.x = element_blank(),
         axis.ticks.y = element_blank(),
         axis.text.y = element_blank(),
         axis.title.y = element_blank(),
         axis.ticks.x = element_blank(),
         axis.text.x = element_blank(),
         axis.title.x = element_blank(),
        plot.title = element_text(hjust = 0.5, vjust = -15)
  )

Current ggplot

deyfvvtc

deyfvvtc1#

问题是你的数据只包含一个obs。因此,填充比例的限制将塌陷为一个点。

max_exit_velo <- data.frame(
  rank = 53,
  MaxExitVelo = 93.1
)

max_rank <- 100

library(ggplot2)

p <- ggplot(max_exit_velo, aes(x = rank, y = "")) +
  geom_point(size = 10, aes(color = rank)) +
  geom_text(aes(label = rank)) +
  geom_label(aes(label = round(MaxExitVelo, digits = 1)), nudge_x = 0, nudge_y = 0.15) +
  ggtitle("Max Exit Velocity") +
  scale_x_reverse(expand = c(0, 0.5), limits = c(max_rank + 1, 0)) +
  theme_linedraw(base_line_size = 5) +
  theme(
    legend.position = "none",
    panel.border = element_rect(color = "white"),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    axis.ticks.y = element_blank(),
    axis.text.y = element_blank(),
    axis.title.y = element_blank(),
    axis.ticks.x = element_blank(),
    axis.text.x = element_blank(),
    axis.title.x = element_blank(),
    plot.title = element_text(hjust = 0.5, vjust = -15)
  )

p + scale_color_gradient2(low = "blue", mid = "white", high = "red")

要解决此问题,请设置填充比例的limits以反映rank的范围:

p + scale_color_gradient2(low = "blue", mid = "white", high = "red", limits = c(0, 100))

此外,您可能需要一个不同于默认值零的中点:

p + scale_color_gradient2(low = "blue", mid = "white", high = "red", midpoint = 50, limits = c(0, 100))

相关问题