shirleywu
shirleywu

Reputation: 674

Make all positive value bar graph the same color theme as bar graph with negative values in ggplot

I just started playing with ggplot yesterday. My code for the bar graph with negative values work as I have expected:

dtf1 <- data.frame(ID = c(1:10),Diff = c(-5:4))
dtf1$colour <- ifelse(dtf1$Diff < 0, "firebrick1","steelblue")
dtf1$hjust <- ifelse(dtf1$Diff > 0, 1.3, -0.3)
ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
  geom_text(aes(y=0,colour=colour))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))

Positive and Negative Value But not so when I apply the same code to a different dataset that has only positive values

dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
dtf$colour <- ifelse(dtf$Diff < 0, "firebrick1","steelblue")
dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
  geom_text(aes(y=0,colour=colour))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))

Only positive values

I find that I can tweak the last line of the code to get blue colors for my positive bars, geom_bar(stat="identity",position="identity",fill="steelblue")

My two questions therefore are:

  1. However, the color isn't as expected:

Positive value - to blue

It seems like the color may be closer to turquoise3 instead of to steelblue.

  1. Moreover, I am also interested in finding why the same code would allow the positive bars to have different colors.

I must have been asking a very simple question. I don't know how best to phrase it and therefore have difficulty finding the solution. I apologize if the question has already been asked and I would be glad to delete myself.

Upvotes: 7

Views: 9634

Answers (1)

jlhoward
jlhoward

Reputation: 59395

Aesthetics don't work that way in ggplot. $colour is treated as a factor with two levels, firebrick1, and steelblue, but these are not the colors ggplot uses. They are just the labels for the color scale. ggplot picks it's own colors. If you want to override the defaults, add the line:

scale_fill_manual(values=c(firebrick1="firebrick1",steelblue="steelblue"))

Compare to this:

dtf1$colour <- ifelse(dtf1$Diff < 0, "negative","positive")
ggplot(dtf1,aes(ID,Diff,label="",hjust=hjust))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))+
  scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))

This works with all positive (or negative).

dtf <- data.frame(ID = c(1:10),Diff = rnorm(10,3))
dtf$colour <- ifelse(dtf$Diff < 0,"negative","positive")
dtf$hjust <- ifelse(dtf$Diff > 0, 1.3, -0.3)
ggplot(dtf,aes(ID,Diff,label="",hjust=hjust))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))+
  scale_fill_manual(values=c(positive="firebrick1",negative="steelblue"))

Upvotes: 10

Related Questions