问题
I am trying to have ggplot2 show one line of a histogram as a different color than the rest. In this I have been successful; however, ggplot is using the default colors when a different set are specified. I am sure there is an error in my code, but I am unable to determine where it is. The data and code are below:
create data
library(ggplot2)
set.seed(71185)
dist.x <- as.data.frame(round(runif(100000, min= 1.275, max= 1.725), digits=2))
colnames(dist.x) <- 'sim_con'
start histogram
ggplot(dist.x, aes(x = sim_con)) +
geom_histogram(colour = "black", aes(fill = ifelse(dist.x$sim_con==1.55, "darkgreen", "firebrick")), binwidth = .01) +
theme(legend.position="none")
Which results in the following image:

I do not want to use the default colors, but instead want to use 'darkgreen' and 'firebrick'. Where is the error in the code? Thanks for any help you can provide.
回答1:
I don't think you can explicitly set colors in aes
; you need to do it in scale_fill_manual
, as in the example below:
ggplot(dist.x, aes(x = sim_con)) +
geom_histogram(colour = "black", binwidth = .01,aes(fill=(sim_con==1.55))) +
scale_fill_manual(values=c('TRUE'='darkgreen','FALSE'='firebrick')) +
theme(legend.position="none")

回答2:
You're so close!
In your code above, ggplot is interpreting your fill as variables in your data set - factor darkgreen
and factor firebrick
- and doesn't have any way of knowing that those labels are colors, not, say, names of animal species.
If you add scale_fill_identity()
to the end of your plot, as below, it will interpret those strings as colors (the identity), not as features of the data.
One benefit of this approach vs @marat's excellent answer above: if you have a complex plot (say, using geom_segment()
, with a starting value and an ending value for each observation) and you want to apply two fill scales on your data (one scale for the start value and a different scale for the end value) you can do the conditional logic in the data processing step, then use scale_fill_identity()
to color each observation accordingly.
ggplot(
data=dist.x,
aes(
x = sim_con,
fill = ifelse(dist.x$sim_con==1.55, "darkgreen", "firebrick")
)
) +
geom_histogram(
colour = "black",
binwidth = .01
) +
theme(legend.position="none") +
scale_fill_identity()
来源:https://stackoverflow.com/questions/28609760/why-is-ggplot-using-default-colors-when-others-are-specified