2

I have a factor which I created as follows:

myfactor<-c("A","B","C","D")
myfactor<-factor(myfactor)

I use that factor for multiple datasets for the value column:

factor(datasetA$value,levels=myfactor)
factor(datasetB$value,levels=myfactor)

Dataset A

            Type   count variable                 value
1:              1   235        1                  A
2:              2    31        1                  A
3:              3    28        1                  B
4:              4   113        1                  B
5:              5    40        1                  C

Dataset B

            Type   count variable                 value
1:              1   235        1                  B
2:              2    31        1                  B
3:              3    28        1                  B
4:              4   113        1                  B
5:              5    40        1                  C

My Problem

When I plot dataset A with the command

  ggplot(data=datasetA, aes(x=as.factor(variable),y=count,fill = value)) + 
    geom_bar(position = "stack", stat = "identity", width = 1) +
    scale_fill_manual(values=c("#4ceb34","#ebd034","#eb34dc","#34ebc3","#3452eb","#eb3434"))

I get the following legend:

enter image description here

When I plot dataset B the legend looks like the following

enter image description here

I want to establish a binding between the levels and the colors: A should be green, B should be yellow... How can I do that?

zx8754
  • 52,746
  • 12
  • 114
  • 209
user3579222
  • 1,103
  • 11
  • 28

1 Answers1

1

The trick is to assign the values to a named vector:

myfactor <- c("A", "B", "C", "D", "E", "F")
vals <- setNames(c("#4ceb34","#ebd034","#eb34dc","#34ebc3","#3452eb","#eb3434"), myfactor)

Note that there is no need to coerce myvector to factor, what is needed is to have colors with names assign to them.
Then, in the plot, use layer

scale_fill_manual(values = vals)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66