John Thomas
John Thomas

Reputation: 1105

Adding color to boxplot in ggplot2

Unsure what's going wrong here but basically I want to create a boxplot filled a specific color using the following:

ggplot(iris %>%  
+            filter(Species == "setosa"), aes(y= Sepal.Length)) + 
+     geom_boxplot(coef = 7)+
+     scale_color_manual(values="cornflowerblue") +
+     labs(title="Sepal Length", y = "Length")+ 
+     theme_hc()

No matter what I try (fill/color ops in aes) I don't get color.

Also, how do I stop the x-axis from being continuous?

Upvotes: 0

Views: 6142

Answers (2)

Oliver
Oliver

Reputation: 8572

It depends on what you're looking for. If you are only creating a single boxplot, you can simply use fill and col outside of aes

library(ggplot2)
library(dplyr)
data(iris)
iris %>% filter(Species == 'setosa') %>%
  ggplot(aes(y = Sepal.Length)) +
  geom_boxplot(col = 'green', fill = 'green')

colour on single boxplot Note that col is the colour of the border while fill is the filling of the box. col=NA works by removing the colour around the boxplot.
But if you wish to get control over the colour with multiple groups, this has to be specified in 2 places

  1. aes(col = group, fill = group), to control the grouping to be coloured
  2. scale_colour_manual / scale_color_manual and scale_fill_manual to control the actual colours chosen for the fill and border respectively.
iris %>% 
  ggplot(aes(y = Sepal.Length, 
             fill = Species, 
             col = Species)) +
  geom_boxplot() + 
  scale_fill_manual(values = c(setosa = 'blue', 
                               versicolor = 'yellow', 
                               virginica = 'orange')) + 
  scale_colour_manual(values = c(setosa = 'purple', 
                                 versicolor = 'green',
                                 virginica = 'black'))

variable colour by group and fill

Upvotes: 3

Duck
Duck

Reputation: 39595

Pointing to comments of @akrun this works:

ggplot(iris %>% filter(Species == "setosa"), aes(y= Sepal.Length)) + 
       geom_boxplot(coef = 7,fill='cornflowerblue')+
       labs(title="Sepal Length", y = "Length")

enter image description here

Upvotes: 2

Related Questions