Search code examples
rggplot2aesthetics

How to assign colors specified within dataframe contents to ggplot geoms?


I am trying to plot a graph of some points with some coloured background regions behind them. I would like the fill colour to be dependent on the "quadrant" name and specified within the dataframe itselt (e.g. "Indifferent" would be pink in the example below). I have tried assigning this column to the values argument of scale_fill_manual, but this appears to have no effect e.g:

quadrant_names <- c("Indifferent", "Must be present", "Attractive", "Performance", "Dislike")
quadrant_xmin <- c(-1, 2, -1, 2, -2)
quadrant_xmax <- c(2, 4, 2, 4, 0)
quadrant_ymin <- c(0, 0, 2, 2, -2)
quadrant_ymax <- c(2, 2, 4, 4, 0)
quadrant_colors <-c("pink", "yellow", "blue", "green", "purple")

kano_quadrants <- data.frame(quadrant_names, quadrant_xmin, quadrant_xmax, quadrant_ymin, quadrant_ymax, quadrant_colors)

xpoints <- runif(10, -2, 4)
ypoints <- runif(10, -2, 4)
points <- data.frame(xpoints, ypoints)

  ggplot(data=points, aes(x=xpoints, y=ypoints)) +
    geom_rect(data=kano_quadrants, aes(xmin=quadrant_xmin, xmax=quadrant_xmax, x=NULL,
                                       ymin=quadrant_ymin, ymax=quadrant_ymax, y=NULL,
                                       fill=quadrant_names), alpha=0.2) +
    geom_point() +
    geom_text(data=kano_quadrants, aes(label=quadrant_names, 
              y=(quadrant_ymin+quadrant_ymax)/2, 
              x=(quadrant_xmin+quadrant_xmax)/2))+
    geom_hline(yintercept=0) +
    geom_vline(xintercept=0) +
    theme_bw() +
    scale_fill_manual(values=kano_quadrants$quadrant_colors)

Results in:

graph

How can I get it to assign the fill colours to the appropriate levels of quadrant_name as specified within the dataframe rather than randomly?


Solution

  • Map fill to quadrant_colors and use scale_fill_identity()

    library(ggplot2)
    ggplot(data=points, aes(x=xpoints, y=ypoints)) +
      geom_rect(data=kano_quadrants, aes(xmin=quadrant_xmin, xmax=quadrant_xmax, x=NULL,
                                         ymin=quadrant_ymin, ymax=quadrant_ymax, y=NULL,
                                         fill=quadrant_colors), alpha=0.2) +
      geom_point() +
      geom_text(data=kano_quadrants, aes(label=quadrant_names,
                                         y=(quadrant_ymin+quadrant_ymax)/2,
                                         x=(quadrant_xmin+quadrant_xmax)/2))+
      geom_hline(yintercept=0) +
      geom_vline(xintercept=0) +
      theme_bw() +
      scale_fill_identity()
    

    enter image description here