R: gradient fill for geom_rect in ggplot2

2020-02-11 08:09发布

I want to create in R a graphic similar to the one below to show where a certain person or company ranks relative to its peers. The score will always be between 1 and 100.

rank

Although I am amenable to any ggplot solution it seemed to me that the best way would be to use geom_rect and then to adapt and add the arrowhead described in baptiste's answer to this question. However, I came unstuck on something even simpler - getting the geom_rect to fill properly with a gradient like that shown in the guide to the right of the plot below. This should be easy. What am I doing wrong?

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()

geom_rect

标签: r ggplot2
1条回答
地球回转人心会变
2楼-- · 2020-02-11 08:48

I think that geom_tile() will be better - use sales for y and fill. With geom_tile() you will get separate tile for each sales value and will be able to see the gradient.

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()

enter image description here

查看更多
登录 后发表回答