us states plot in R with election results - r

I have plotted a figure of the US states in R.
Here is the very simple code:
library(usmap)
library(ggplot2)
plot_usmap(region = 'states')
And here is the resulting figure:
Figure of US states in R - states are not colored
Furthermore, I have a csv file containing the names of the states in US, and a color value, equal to red if that state voted for Republicans or blue if the state voted for Democrats. This is the top 5 rows of the CSV file:
State
Color
Alabama
#E81B23
Alaska
#E81B23
Arizona
#1405bd
Arkansas
#E81B23
How can I fill the states of my figure based on the colors in the CSV file?

To color the regions specified in the plot_usmap() function, you can provide your data via data= and then set the values= argument to the column in your data used for mapping the colors.
Here's an example with some randomly-generated data. The plot_usmap() is using a dataset that includes the 50 US states + the District of Columbia, so you'll want to make sure they are all in your dataset or you may get some NA labels.
library(usmap)
library(ggplot2)
set.seed(1234)
color_data <- data.frame(
state = c(state.name, "District of Columbia"),
the_colors = sample(c("A", "B"), size=51, replace=TRUE)
)
plot_usmap(
region = "states",
data = color_data,
values = "the_colors",
color="white"
) +
scale_fill_manual(values=c("#E81B23", "#1405bd"))
Note that I think the lines between the states look good in white, so color="white" fixes that. You may also notice that you typically don't specify the actual color in the dataframe - you can specify that via scale_fill_manual(values=...). In your case, you can use scale_fill_identity().
For your data, just make sure the "States" column in your dataset is renamed "state" and it should work.

Related

How to plot data on map without coordinates?

I am trying to plot dataframe like:
code name description estimate
0 Australia Vegetables 854658
0 Australia Fruit 667541
1 New South Wales Vegetables 45751
1 New South Wakes Fruit 77852
2 Victoria Vegetables 66211
2 Victoria Fruit 66211
.
.
.
For each region in Australia there are multiple rows with different description. What packages may I use to plot a map with estimate without coordinates?
I try ggplot and ozmaps with sf which mentioned in ggplot2 tutorial, and I filter the dataframe for only fruit, but there is error message :
stat_sf requires the following missing aesthetics: geometry
the code I tried :
ggplot() +
geom_sf(oz_states,mapping=aes())+
geom_sf(df,mapping=aes()) +
coord_sf()
The methods I found are all required langitude and latitude to plot the data map, I tried ggmaps or geom_ploygon but didn't figure out the correct way to do so. Is there a possible way to plot map with only region labels?
this is what I plot by tableau, and this is expected plot by using r as well:
So essentially, your first problem is that you're calling the wrong object within the ozmaps package. it's ozmap_states, meanwhile you called yours oz_states
I came up with this solution that I think takes what you want and elevates it.
df <- data.frame(code = rep(c(0,1,2), 2), name = rep(c("Australia", "New South Wales", "Victoria"), 2), description = rep(c("Vegetables", "Fruit"), 3), count =
c(854658, 45751, 66211, 667541, 77852, 66211))
library(tidyverse)
library(sf)
library(ozmaps)
library(leaflet)
library(tmap)
states_full <- right_join(df, ozmap_states, by = c("name" = "NAME"))
data <- states_full %>%
filter(description == "Fruit") %>%
select(name, geometry, count)
ozmap1 = tm_shape(ozmap_states) +tm_polygons()
tmap_mode("view")
ozmap1 + tm_shape(st_as_sf(data)) + tm_fill(col = "count")
Basically, instead of using the sample dataframe that I created from your data, you would just use your data in the right join. You can also choose whether you want fruits or vegetables in your filter function.
The tmap package is a mapping package that can make interactive leaflet like maps.
You can look at some tutorials here: https://geocompr.robinlovelace.net/adv-map.html
End solution looks something like this.
Note: This solution uses lng/lat, but it pulls it directly from the shape file for oz state maps in the ozmaps package, therefore fulfilling the need of the question.
When you add in more data, more of Australia will be colored in depending on their count.

ggplot aesthetics don't accommodate for a variable name

So I'm plotting a shape file (from the ONS) of Great Britain split into 11 regions with the hope of creating a choropleth map based on COVID-19 cases.
I join the covid data with the shape file so that I can work within 1 data frame, joining on the region name.
I've used the longitude and latitude fields of the shape file for the x and y values within the aesthetics.
covid <- data.frame(Name = c("Scotland","Eastern","West Midlands","Yorkshire and the Humber","East Midlands","London","South West","South East","North West","North East","Wales"),
Cases = c(20,50,45,30,25,75,100,5,60,35,80))
#'greatb' is the name of the shape file
join <- merge(greatb,covid,by=c("NAME","Name"),by.x=c("NAME"),by.y=c("Name"), all=TRUE)
ggplot()+
geom_polygon(data=join, aes(x=long, y=lat, group=group, fill=Cases))
However, it seems that once I do this I can't use a variable name to fill the regions of the map. I get confronted with the error message: object 'Cases' not found
I'm unsure why I get this is message though as 'covid$data' is clearly an object and therefore so is 'join$data'. Can anyone help me with this?

How to display only some country names with tm_text in R

I have created a map of Africa in R, using tmap, showing some numerical variables, but I would like to show the name of the countries only for the countries where the numerical variable is not 0.
So I have created a colour vector containing the value 'black' when the numeric was >0 and NA when it was =0. For a lot of functions, this will allow to display only the 'black' labels and not the NA ones, but with tm_text the NA values are shown in white on the map.
Map image
I tried to use several of the tm_text options, but nothing worked. If I change the NA with a colour name it works, the labels are displayed in the colour I indicated, but NA doesn't allow to make the labels disappear.
spdf_africa <- ne_countries(continent = 'africa',type="map_units",scale = "medium", returnclass = "sf")
xx<-numeric(length=57)
xx[match(names(tole),spdf_africa$name)]<-tole
xxcol<-xx
xxcol[xx>0]<-"black"
xxcol[xx==0]<-NA
afric=spdf_africa
afric$studies<-xx
afric$studiesTF<-xxcol
tm_shape(afric)+tm_fill(col="studies",title="Nb",style="cat")+tm_text("iso_a3",col="studiesTF",size=0.8)+tm_borders()
Of course I could use the pale yellow as label colour for the countries I don't want to display but these labels would still be visible when they overlap with borders or neighbouring countries.
Is there a way to do that more elegantly?
Thank you
There are, as usual, many different solutions.
You could just create another africa data frame (sfc), only with the features that you need, i.e. x>0 and go
tm_shape(afric) +
tm_fill(col="studies",title="Nb",style="cat") +
tm_borders() +
tm_shape(afric_selection) +
tm_text("iso_a3)
Reproducible Example
# load library
library(tmap)
# get world data set (sf)
data(World)
# create two shapes, one with border, one with selection (life expectancy bigger then 80 years) and only text
tm_shape(World) + tm_borders() +
tm_shape(World[World$life_exp > 80, ]) + tm_text("iso_a3")
Or the tidyverse way
tm_shape(World) +
tm_borders() +
tm_shape(World %>% filter(life_exp > 80)) +
tm_text("iso_a3")

Creating a map plot in R using plot_usmap package

I have a dataset containing different states, zip codes, and claim counts each in separate columns. I am trying to create a plot to show the total claim count according to zip codes for the state of MA.
Dataset:
I used this to filter by MA:
MA_medicare <- medicare %>%
filter(medicare$NPPES.Provider.State == "MA")
I then used this to set the fips code for plot_usmap:
MA_medicare$NPPES.Provider.State <- fips(MA_medicare$NPPES.Provider.State)
setnames(MA_medicare, old=c("NPPES.Provider.State"), new=c("fips"))
And last tried to graph (not sure why this doesn't work):
plot_usmap(data = MA_medicare, values= c("Total.Claim.Count", "NPPES.Provider.Zip.Code"), include = c("MA")) + scale_fill_continuous(low= "white", high= "red") + theme(legend.position = "right")
Error: Aesthetics must be either length 1 or the same as the data (4350838): fill
I'm the developer of usmap. plot_usmap only accepts one column of values for plotting so you're probably looking for the following:
plot_usmap(data = MA_medicare, values = "Total.Claim.Count", include = c("MA"))
However, your data is by zip code, and currently usmap doesn't support zip code maps (only state and county level maps). It uses the FIPS column to assign colors to states/counties on the map. Since you defined the FIPS codes by state, you'll just get the entire state of Massachusetts filled in with one solid color.

How to use regions' names as labels in spatial Data?

I use the following code to visualize some SpatialPolygonsDataFrame with ggplot2:
require(shapefiles)
require(sp)
xx <- readShapeSpatial(system.file("shapes/sids.shp", package="maptools")[1],
IDvar="FIPSNO", proj4string=CRS("+proj=longlat +ellps=clrk66"))
xx.ff <- fortify(xx,region="NAME")
x <- ggplot(xx.ff) +
aes(long,lat, fill = id) +
geom_polygon()
to end up with:
Assume that I am using fill to represent something else, like regional theft rate. Thus I want to label those regions with their names. is there a way to write the regions name right onto the map into the corresponding region, e.g. I want to write Halifax right onto the region.
Have a look at similar/related questions I asked:
ggplot centered names on a map
Improve centering county names ggplot & maps
Plot county names on faceted state map (ggplot2)

Resources