Home > database >  Colours don't show up in bar plot using ggplot2
Colours don't show up in bar plot using ggplot2

Time:02-03

When I try to assign colours using colour = "" or fill = """, the graph changes its colour always to the same colour (some kind of weird orange tone). The specific code I used is this: Plot <- ggplot(data, aes(ymin = 0)) geom_rect(aes(xmin = left, xmax = right, ymax = a, colour = "#FDFEFE")). Has anyone had this problem before? It doesn`t seem to matter whether I use the colour names or the HTML codes, the result stays the same. Thank you!

CodePudding user response:

I just wanted to add some explanation because this also tripped me up when I started using ggplot.

Some toy data:

data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20   10)

As explained by @stefan, you need to set the hard-coded color outside of the aestetics:

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a), fill = "#FDFEFE")

The aestetics are meant to link the plot to your data table. When you write this:

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = "#FDFEFE"))

It is like having the following:

data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20   10, col = "#FDFEFE")

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col))

Except that ggplot understands "#FDFEFE" as a categorical value, not as a color. Having "#FDFEFE" or "banana" is the same to ggplot:

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = "banana"))

or

data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20   10, col = "banana")

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col))

assign default colours to the categorical data.

As an extra, if you want to assign specific colors to different entries in the table, it is best to use a scale_*_manual layer:

data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20   10,
               col = sample(c("banana", "orange", "coconut"), 10, replace = T))

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a, fill = col))  
  scale_fill_manual(values = c("banana" = "yellow2", "orange" = "orange2", "coconut" = "burlywood4"))

If you wanted to hard-code the colors in the table, you would have to use this column outside to the aestetics:

data <- tibble(a = 1:10, left = 1:10 * 20, right = 1:10 * 20   10,
               col = sample(c("yellow2", "orange2", "burlywood4"), 10, replace = T))

ggplot(data, aes(ymin = 0))  
  geom_rect(aes(xmin = left, xmax = right, ymax = a), fill = data$col)

But it is best to use meaningful categorical values and assign the colors in the scale layer. This is what the grammar of graphics is all about!

  •  Tags:  
  • Related