R:ggplot2 中 geom_rect 的渐变填充

Slo*_*ner 3 r ggplot2

我想在 R 中创建一个类似于下面的图形来显示某个人或公司相对于其同行的排名。分数总是在 1 到 100 之间。

秩

尽管我可以接受任何ggplot解决方案,但在我看来,最好的方法是使用geom_rect然后调整并添加 baptiste 对这个问题的回答中描述的箭头。然而,我发现了一些更简单的东西 -geom_rect使用如下图右侧的指南中所示的渐变正确填充。这应该很容易。我究竟做错了什么?

library(ggplot2)
library(scales)

mydf <- data.frame(id = rep(1, 100), sales = 1:100)

ggplot(mydf) +
    geom_rect(aes(xmin = 1, xmax = 1.5, ymin = 0, ymax = 100, fill = sales)) +
    scale_x_discrete(breaks = 0:2, labels = 0:2) +
    scale_fill_gradient2(low = 'blue', mid = 'white', high = 'red', midpoint = 50) +
    theme_minimal()
Run Code Online (Sandbox Code Playgroud)

geom_rect

Did*_*rts 5

我认为这geom_tile()会更好 -sales用于yand fill。随着geom_tile()你会得到每个销售值分别瓦,将能够看到的梯度。

ggplot(mydf) +
  geom_tile(aes(x = 1, y=sales, fill = sales)) +
  scale_x_continuous(limits=c(0,2),breaks=1)+
  scale_fill_gradient2(low = 'blue', mid = 'white', high = 'red', midpoint = 50) +
  theme_minimal()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明