有了这个数据:
df <- data.frame(value =c(20, 50, 90),
group = c(1, 2,3))
我可以得到一个条形图:
df %>% ggplot(aes(x = group, y = value, fill = value)) +
geom_col() +
coord_flip()+
scale_fill_viridis_c(option = "C") +
theme(legend.position = "none")
但我希望这些条形的颜色根据其相应的值而变化value
.
我已经设法使用更改它们geom_raster
:
ggplot() +
geom_raster(aes(x = c(0:20), y = .9, fill = c(0:20)),
interpolate = TRUE) +
geom_raster(aes(x = c(0:50), y = 2, fill = c(0:50)),
interpolate = TRUE) +
geom_raster(aes(x = c(0:90), y = 3.1, fill = c(0:90)),
interpolate = TRUE) +
scale_fill_viridis_c(option = "C") +
theme(legend.position = "none")
当我在实际数据中有很多组时,这种方法效率不高。任何能够更有效地完成工作的建议将不胜感激。
I found 先前类似问题的已接受答案 https://stackoverflow.com/questions/48210231/creating-a-vertical-color-gradient-for-a-geom-bar-plot,但是“这些数字需要根据 x 值的数量和 y 的范围进行调整”。我一直在寻找一种不必根据数据调整数字的方法。大卫·吉布森的回答符合我的目的。