1

I made a stacked area charts using ggplot2 like this

ggplot(data, aes(x=time, y=value, fill=group)) + 
  geom_area()+
  scale_fill_manual(values = c("black", "red", "yellow", "purple", "deeppink", "blue"))

In the group variable appear 6 different strings values identifying the groups, how can I assign one precise color to each group?

Furthermore is it possible to order the groups in the chart with the same order as they appear in the data I am passing to the function? Otherwise how can I decide the order?

Shankar
  • 2,890
  • 3
  • 25
  • 40
Claudio P
  • 165
  • 1
  • 8

1 Answers1

0

It doesn't matter whether it's fill or color. The plot type also doesn't matter.

You can use key-value pairs to specify the color or fill as long as the values provided in values argument is inside the column for coloring.

In following example, setosa, versicolor and virginica are three unique values in Species column.

ggplot(iris,aes(x = Sepal.Width, y = Sepal.Length, color = Species)) +
    geom_point() +
    scale_color_manual(values = c(
        "setosa" = "black",
        "versicolor" = "red",
        "virginica" = "green"
    ))

enter image description here

yusuzech
  • 5,896
  • 1
  • 18
  • 33
  • I substituted the scale_fill_manual function with: scale_color_manual(values = c( "MAXC" = "black", "MAXD" = "red", "MINC" = "yellow", "MIND" = "purple", "RND" = "blue", "NO" = "deeppink" )) the "MAXC" ecc are the string representing the groups, but it didn't work and the standard colors of the chart have been used. – Claudio P Oct 07 '19 at 20:44
  • I had to use still the scale_fill_manual function instead of the scale_color_manual but passed the key, value list as you said, and it worked. What about the order? – Claudio P Oct 07 '19 at 20:49
  • To change the order of stacking, you need to make `group` an ordered factor. `forcats` is a handy package for dealing with factors, and `forcats::fct_inorder()` should help you put your groups in order of appearance. https://forcats.tidyverse.org/ – Jon Spring Oct 07 '19 at 20:51
  • If you use `fill` in `aes()` then use `scale_fill_*`, if you use `color` in `aes()` then use `scale_color_*`. – yusuzech Oct 07 '19 at 20:54
  • Please see https://stackoverflow.com/questions/32345923/how-to-control-ordering-of-stacked-bar-chart-using-identity-on-ggplot2 ; If what you ask is irrelevant to your question. Either ask a new question, or modify your original question. – yusuzech Oct 07 '19 at 21:15