I'm trying to plot a map of a categorical variable using ggplot2, where states are shaded one color if they at any point introduced a certain bill, and another color if they never have. The shading appears to work, but the geom objects do not properly fit the state borders (
).
I'm not sure why this is the case. Here's the code I used:
all_states <- map_data("state")
all_states <- rename(all_states,
state = "region")
all_states$state <- str_to_title(all_states$state)
# select states that introduced bill
int <- read_csv("int.csv", col_types = cols(introduced = col_integer()))
statelist <- int$state
statelist <- state.name[match(statelist, state.abb)]
int <- cbind(statelist, int)
int <- select(int, statelist, introduced)
int <- rename(int,
state = statelist)
stateData <- merge(all_states, int, by="state")
# plot bill introduction
plot1 <- ggplot()
geom_polygon(data=stateData, aes(x=long, y=lat,
group=group, fill = as.factor(introduced)), color = "grey50")
coord_map()
CodePudding user response:
The issue is most likely that the merge breaks the order of the maps dataframe given by the order column, i.e. geom_polygon will connect the points in the order as they appear in the dataset.
Using some fake random example data I can reproduce your issue:
library(stringr)
library(ggplot2)
all_states <- map_data("state")
all_states <- dplyr::rename(all_states,
state = "region"
)
all_states$state <- str_to_title(all_states$state)
library(ggplot2)
library(dplyr, warn = FALSE)
int <- data.frame(
state = state.name,
introduced = sample(c(0, 1), 50, replace = TRUE)
)
stateData <- merge(all_states, int, by = "state")
ggplot()
geom_polygon(data = stateData, aes(x = long, y = lat, group = group, fill = as.factor(introduced)), color = "grey50")
coord_map()

To fix that we could re-arrange the data by the order column (per state and group)
stateData <- stateData |>
arrange(state, group, order)
ggplot()
geom_polygon(data = stateData, aes(x = long, y = lat, group = group, fill = as.factor(introduced)), color = "grey50")
coord_map()

