I am plotting data with ggplot in R and trying to map colors to fruits through a column in the dataframe. I expect scale_fill_identity()
to map these fills to geom_col()
, but it switches the colors of two fruits. Reproducible snippet below:
f <- tibble(
fruit=factor(c('banana','apple','clementine'),c('clementine','banana','apple')),
value=c(20, 30, 50),
color=c('yellow','red','orange'),
)
# table is as-expected
# bananas are yellow, apples are red, clementines are orange
f
# factors ordered properly
f |> count(fruit)
# auto colors look fine
f |> ggplot(aes('x', value, fill=fruit)) geom_col()
# bananas are red, apples are yellow
f |> ggplot(aes('x', value, fill=color)) geom_col()
scale_fill_identity(guide='legend', labels=levels(f$fruit))
# why are colors not matching the mapping i have in the table?
# should i be using something like breaks=f$color in the identity call?
What am I missing, shouldn't I be able to use map colors like this? I know I can provide a named vector in values
of scale_fill_manual()
, but I'd rather add values to the dataframe. Also, should I be using the breaks
argument?
CodePudding user response:
You should add your breaks
of your "color" column and remove levels
from your labels
like this:
library(tibble)
library(ggplot2)
f <- tibble(
fruit=factor(c('banana','apple','clementine'),c('clementine','banana','apple')),
value=c(20, 30, 50),
color=c('yellow','red','orange'),
)
f |> ggplot(aes('x', value, fill=color)) geom_col()
scale_fill_identity(guide='legend', labels=f$fruit, breaks = f$color)
Created on 2022-09-17 with reprex v2.0.2
Reverse order legend using rev
:
f |> ggplot(aes('x', value, fill=color)) geom_col()
scale_fill_identity(guide='legend', labels=rev(f$fruit), breaks = rev(f$color))
Created on 2022-09-17 with reprex v2.0.2