Reputation: 1
I am trying to change the default fill color from blue to green or red. Here is the code I am using
Top_pos<- ggplot(Top_10, aes(x=reorder(Term,Cs), y=Cs, fill=pvalue)) +
geom_bar(stat = "identity", colour="black") + coord_flip()
Using the above code, I get the following image. I have no problem with this data but I do not know how to change the fill color.
Upvotes: 0
Views: 1376
Reputation: 16832
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).
Upvotes: 1
Reputation: 737
Personally, I'm a fan of R Color Brewer. It's got a set of built-in palettes that play well together for qualitative, sequential or diverging data types. Check out colorbrewer2.org for some examples on real-ish data
More generally, and for how to actually code it, you can always add a scale_fill_manual
argument. There are some built-ins in ggplot2
for gradients (examples here)
Upvotes: 0