Why is ggplot using default colors when others are specified?

前端 未结 2 1853
春和景丽
春和景丽 2021-01-14 16:28

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 whe

2条回答
  •  无人及你
    2021-01-14 17:04

    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()
    

提交回复
热议问题