首页 > 解决方案 > 如何更改 geom_bar 中计算变量的填充颜色

问题描述

我正在尝试将默认填充颜色从蓝色更改为绿色或红色。这是我正在使用的代码

Top_pos<- ggplot(Top_10, aes(x=reorder(Term,Cs), y=Cs, fill=pvalue)) + 
    geom_bar(stat = "identity", colour="black") + coord_flip() 

使用上面的代码,我得到以下图像。我对这些数据没有问题,但我不知道如何更改填充颜色。

当前颜色的条形图

标签: rggplot2geom-bar

解决方案


It's easy to confuse scaling the color and scaling the fill. In the case of geom_bar/geom_col, color changes the borders around the bars while fill changes the colors inside the bars.

You already have the code that's necessary to scale fill color by value: aes(fill = pvalue). The part you're missing is a scale_fill_* command. There are several options; some of the more common for continuous scales are scale_fill_gradient or scale_fill_distiller. Some packages also export palettes and scale functions to make it easy to use them, such as the last example which uses a scale from the rcartocolor package.

scale_fill_gradient lets you set endpoints for a gradient; scale_fill_gradient2 and scale_fill_gradientn let you set multiple midpoints for a gradient.

scale_fill_distiller interpolates ColorBrewer palettes, which were designed for discrete data, into a continuous scale.

library(tidyverse)

set.seed(1234)
Top_10 <- tibble(
    Term = letters[1:10],
    Cs = runif(10),
    pvalue = rnorm(10, mean = 0.05, sd = 0.005)
)

plt <- ggplot(Top_10, aes(x = reorder(Term, Cs), y = Cs, fill = pvalue)) +
    geom_col(color = "black") +
    coord_flip()

plt + scale_fill_gradient(low = "white", high = "purple")

plt + scale_fill_distiller(palette = "Greens")

plt + rcartocolor::scale_fill_carto_c(palette = "Sunset")

Created on 2018-05-05 by the reprex package (v0.2.0).


推荐阅读