R Geom Point - Data disappearing after Color Palette

45 Views Asked by At

I have this geom point, that shows the Sales Ratio of 30 towns from Connecticut, works well and this is the chart.

enter image description here

Once I add a color palette (last line of code), it removes 22 data rows. *Removes 21 rows containing missing values ( geom_point() ) *

Any ideas?

enter image description here

This is the code.

  sales %>% group_by(Town) %>%
    summarise(ratio_mean = mean(Sales.Ratio)) %>%
    arrange(-ratio_mean) %>%
    subset(ratio_mean < 3 & ratio_mean >0.1) %>%
    head(30) %>%
    ggplot(aes(x = ratio_mean, y = reorder(Town, ratio_mean), color=Town)) +
    geom_point(size=4) +
    theme_bw() +
    theme(panel.grid.major.x=element_blank(),
          panel.grid.minor.x=element_blank(),
          panel.grid.major.y=element_line(linetype="dashed",color="gray"),
          legend.position = "none")+
    labs(x="Sales Ratio",y="Town", 
         title="Top 30 Towns with the highest Sales Ratio",
         subtitle = "Units that were sold over the listed price") +
    scale_color_brewer(palette = 'Greens')
1

There are 1 best solutions below

0
stefan On

As pointed out by @GeorgeSavva in his comment each brewer palette has a maximum number of colors. One option to circumvent this limitation would be to use colorRampPalette which via interpolation allows to create a color palette with in general any number of colors which could then be passed to scale_color_manual.

library(ggplot2)

dat <- data.frame(
  x = 1:30
)
dat$y <- factor(dat$x)

pal_color <- colorRampPalette(scales::brewer_pal(palette = "Greens")(9))(30)

ggplot(dat, aes(x, y, color = y)) +
  geom_point(size = 8) +
  scale_color_manual(values = pal_color) +
  guides(color = "none")