Neuro H
Neuro H

Reputation: 79

How do I assign colors to my ggplot?

I'm new to using ggplot. I'm looking to just specify the colors I want for the group (i.e. High = red4; Low = gray45). Group is defined by "high" or "low" values.

ggplot(my_data, aes(x=continuous_variable, fill=Group)) + geom_histogram() + 
  xlab("continuous_variable")+ 
  ylab("Frequency") + 
  ggtitle("My Variable")

Upvotes: 1

Views: 77

Answers (1)

Thomas K
Thomas K

Reputation: 3311

Axeman pointed you already into the right direction: just add scale_fill_manual to your code.

Reproducible example:

library(ggplot2)

# sample data
set.seed(1234)
continuous_variable <- rnorm(100)
Group <- factor(rep(c("high", "low"), 50))
my_data <- data.frame(continuous_variable, Group)

# just add another line to your initial code
ggplot(my_data, aes(x = continuous_variable, fill = Group)) + geom_histogram() + 
  xlab("continuous_variable") + 
  ylab("Frequency") + 
  ggtitle("My Variable") + 
  scale_fill_manual(values = c("high" = "red4", "low" = "grey45"))
#> stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.

Upvotes: 2

Related Questions