Reputation: 15
I am creating a side-by-side boxplot that is colored by hex colors. I seem to have it working, but am unable to get the legend (on the right of the plot) to have the cut labels (Ex: "Fair" instead of "#F8766D"). Here is a MWE that mimics my problem:
library(ggplot2)
library(dplyr)
df <- diamonds[sample(1:nrow(diamonds), size = 1000),]
colList = scales::hue_pal()(5)
df <- as.data.frame(df)
df <- df %>% select("cut","price")
saveColor <- df %>% transmute(color = plyr::mapvalues(cut, c("Fair", "Good", "Very Good", "Premium", "Ideal"), colList))
df$color <- unlist(saveColor)
ggplot(df, aes(cut, price)) + geom_boxplot(aes(fill = factor(color))) + scale_colour_manual(labels = c("Fair", "Good", "Very Good", "Premium", "Ideal"), values = colList)
Upvotes: 0
Views: 979
Reputation: 17790
Not sure what exactly it is that you're trying to do, but in general you wouldn't add the colors as a column into the dataset. Instead, you just provide them as values to the color scale. Also note how much simpler that makes your code.
df <- diamonds[sample(1:nrow(diamonds), size = 1000),]
colList = scales::hue_pal()(5)
df <- df %>% select("cut","price")
ggplot(df, aes(cut, price)) +
geom_boxplot(aes(fill = cut)) +
scale_fill_manual(values = colList)
Upvotes: 2