Rob Rosene
Rob Rosene

Reputation: 35

How do I conditionally color in a US States map using ggplot?

My goal is to show states below sales average as red, and those above as green. My code seems to just be doing some sort of outline of the colors, and I have no idea where the blue fill is coming from. Actual data has all the states, but I just made 5 examples for the purposes of this.

    library(ggplot2)
    library(tidyverse)
    library(mapdata)
    library(dplyr)
    
    MainStates <- map_data("state")
    State_Name <- c("alabama","arkansas","arizona","california","colorado")
    Sales <- c(100,200,250,275,310)
    df2 <- data.frame(State_Name,Sales)
    MergedStates <- inner_join(MainStates, df2, by = c("region" = "State_Name"))

    p <- ggplot() + geom_polygon(data = MergedStates,
                         aes(x=long, y=lat, group=group, fill=Sales),
                         color = ifelse(MergedStates$Sales <= 
                         mean(MergedStates$Sales),"red","green"), size = 0.2)
    p

Upvotes: 1

Views: 889

Answers (1)

Bart
Bart

Reputation: 1382

I think this is what you want to achieve? In geom_sf color refers to the color of the border and fill to the color filing the polygons (for polygons).

library(ggplot2)
library(tidyverse)
library(mapdata)
#> Loading required package: maps
#> 
#> Attaching package: 'maps'
#> The following object is masked from 'package:purrr':
#> 
#>     map
library(dplyr)

MainStates <- map_data("state")
State_Name <- c("alabama","arkansas","arizona","california","colorado")
Sales <- c(100,200,250,275,310)
df2 <- data.frame(State_Name,Sales)
MergedStates <- inner_join(MainStates, df2, by = c("region" = "State_Name"))

p <- ggplot() + geom_polygon(data = MergedStates,
                             aes(x=long, y=lat, group=group),
                             fill = ifelse(MergedStates$Sales <= 
                                              mean(MergedStates$Sales),"red","green"), size = 0.2)
p

Created on 2021-10-01 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions