1

I have a colour data frame that I join with my input data to match the colours to categories. The issue is that when using fill=mycolour the legend displays the colour names and not the names of my categories.

I would like fill to be name_assigned while still matching the colours in mycolors.

  df %>%
  dplyr::left_join(colors.variable, by="name_assigned") %>%
  ggplot(aes(reorder(chr,chr,function(x)-length(x)),y=name_assigned, fill=mycolors)) + 
  geom_bar(aes(y = (..count..))) +   
  scale_fill_identity() 
stefan
  • 90,330
  • 6
  • 25
  • 51
user2300940
  • 2,355
  • 1
  • 22
  • 35
  • 1
    Instead of using a join and `scale_fill_identity` you could use a named vector of colors, map `name_assigned` on fill and use `scale_fill_manual`. For more help I would suggest to provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Dec 12 '22 at 09:35
  • 1
    In addition to what @stefan says, your code is unnecessarily verbose. You can remove `y=name_assigned`, since you are using the count for the y variable. This would also allow you to remove `aes(y = (..count..))` from inside `geom_bar`, which by default maps the count to the y axis. In any case, the `..count..` syntax has been deprecated in favour of `after_stat(count)` in the latest version of ggplot2. – Allan Cameron Dec 12 '22 at 09:39

1 Answers1

1

You don't need the join, from the colors data set create a named colors vector and use it in scale_fill_manual.

Also, you seem to have swapped x and y coordinates.

library(ggplot2)

set.seed(2022)
df <- data.frame(
  chr = rbinom(1e3, 1, 0.5),
  name_assigned = sample(letters[1:3], 1e3, TRUE)
)

colors.variable <- data.frame(
  name_assigned = letters[1:3],
  mycolors = c("pink", "purple", "seagreen")
)
mycolors <- with(colors.variable, setNames(mycolors, name_assigned))

ggplot(df, aes(name_assigned, fill = name_assigned)) + 
  geom_bar() +   
  scale_fill_manual(values = mycolors) 

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66