Add your own color palette and adjust the legend

Hello,
I don't know if I'm in the right topic but here's my question.
I created a histogram with ggplot with quite a few variables.
The default colors generated by R are not that distinct. So I used the polychrome package for myself to create my color palette according to my number of variables.
Problem I can't integrate it into my ggplot..

Also, I'd like the legend to be displayed in descending order, so the first variable that's displayed (with its associated color) is the one with the highest value.

#create my own color palette :
P20 = createPalette(20, c("#ff0000", "#00ff00", "#0000ff"))
swatch(P20)

#Ggplot
df%>%
pivot_longer(
cols = Sp1 : Sp20,
names_to = "species",
values_to = "number"
) %>%
filter(!is.na(number)) |>
ggplot(aes(x = reorder(Station,number), y = number)) +
geom_col(aes(fill = species), width = 0.7) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_brewer(palette = "Paired")

Here I used the "Paired" palette from the RColorBrewer package because they are really distinct but there are only 12..
To add my P20 palette I tried with scale_fill_manual (values= P20) but it doesn't work..

Hope you understand^^

I do not have the package Polychrome but it seems like using scale_fill_manual(value =P20) should work. Please post the output of running

P20 = createPalette(20, c("#ff0000", "#00ff00", "#0000ff"))
str(p20)

Try this:

https://cran.r-project.org/web/packages/Polychrome/vignettes/testgg.html

Here is the key point of this entire vignette: By default, Polychrome gives names to each of the colors in a palette. But, in ggplot, named colors will only be applied if they match the levels of an appropriate factor in the data. The simplest solution is to remove the names:

names(P40) <- NULL

@FJCC , @Matthias

Thank to you both !
I combined your two answers and it worked!
For info after performing the "tutorial" of @Matthias' link with this data preparation: :

P20 = createPalette(20,  c("#ff0000", "#00ff00", "#0000ff"))
swatch(P20)
p20 <- sortByHue(P20)
P20 <- as.vector(t(matrix(P20, ncol=4)))
swatch(P20)
names(P20) <- NULL

Created on 2022-02-17 by the reprex package (v2.0.1)

However the tutorial used '''scale_color_manual (P20)''', which didn't work,
So I used '''scale_fill_manual(values=P20)''' as suggested @FJCC !

scale_fill_manual(values = P20)

Created on 2022-02-17 by the reprex package (v2.0.1)

Thanks a lot !

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.