When asking questions about code here, you should start by making sure you’re following the advice in our FAQ: Tips for writing R-related questions. That makes it easier for people to understand your problem and therefore helps you get better answers, faster!
That said, here’s an example using one of R’s built-in datasets that might help explain the error message you’re seeing:
library("ggplot2")
ggplot(data = warpbreaks, aes(x = wool, y = breaks)) +
geom_boxplot(
notch = T,
fill = c("blue", "red", "green3", "hotpink2"),
outlier.color = NULL
) +
theme(legend.position = "none") +
theme_classic()
#> Error: Aesthetics must be either length 1 or the same as the data (2): fill
Created on 2018-10-04 by the reprex package (v0.2.1)
So why the error? The error message says that the aesthetics must be either length 1, or the same length as the data, tells us that the data have a length of 2, and says that the message applies to the fill
aesthetic. The implication is that we have supplied more than 2 fills (or 1 fill, in which case ggplot
would have just repeated it across all the data).
As @jdlong suggested, this code is trying to map a fixed set of fills to the data, and therein lies the problem. There are 4 fill colors. We’re expecting one color per boxplot. So how many boxplots do we have?
levels(factor(warpbreaks$wool))
#> [1] "A" "B"
As the error message tried to say, there are two groups in our x
variable. ggplot
doesn’t understand how to map 4 fixed fill colors to 2 groups.
One solution is to only supply 2 fixed fill colors:
ggplot(data = warpbreaks, aes(x = wool, y = breaks)) +
geom_boxplot(
notch = T,
fill = c("blue", "red"),
outlier.color = NULL
) +
theme_classic() +
theme(legend.position = "none")
(Note that I reversed the order of the theme()
and theme_classic()
calls. This is because theme_classic()
sets legend.position = "right"
, turning the legend back on.)
However, I suspect from your use of aes_string()
that you might be hoping to reuse this plotting code inside a function. In that case, it would be a better idea to supply your colors as a manual scale. Unlike a fixed aesthetic, a manual scale doesn’t mind if there are more colors than data groups.
box_fills <- c("blue", "red", "green3", "hotpink2")
ggplot(data = warpbreaks, aes(x = wool, y = breaks)) +
geom_boxplot(aes(fill = wool),
notch = T,
outlier.color = NULL) +
scale_fill_manual(values = box_fills,
guide = "none") +
theme_classic()
Created on 2018-10-04 by the reprex package (v0.2.1)
Now that we’re calling scale_fill_manual()
, we can also turn off the legend right there (using guide = "none"
), saving a step.