Change colour scheme for ggplot geom_polygon in R - r

I'm creating a map using the maps library and ggplot's geom_polygon. I'd simply like to change the default blue, red, purple colour scheme to something else. I'm extremely new to ggplot so please forgive if I'm just not using the right data types. Here's what the data I'm using looks like:
> head(m)
region long lat group order subregion Group.1 debt.to.income.ratio.mean ratio total
17 alabama -87.46201 30.38968 1 1 <NA> alabama 12.4059 20.51282 39
18 alabama -87.48493 30.37249 1 2 <NA> alabama 12.4059 20.51282 39
19 alabama -87.52503 30.37249 1 3 <NA> alabama 12.4059 20.51282 39
20 alabama -87.53076 30.33239 1 4 <NA> alabama 12.4059 20.51282 39
21 alabama -87.57087 30.32665 1 5 <NA> alabama 12.4059 20.51282 39
22 alabama -87.58806 30.32665 1 6 <NA> alabama 12.4059 20.51282 39
> head(v)
Group.1 debt.to.income.ratio.mean ratio region total
alabama alabama 12.40590 20.51282 alabama 39
alaska alaska 11.05333 33.33333 alaska 6
arizona arizona 11.62867 25.55556 arizona 90
arkansas arkansas 11.90300 5.00000 arkansas 20
california california 11.00183 32.59587 california 678
colorado colorado 11.55424 30.43478 colorado 92
Here's the code:
library(ggplot2)
library(maps)
states <- map_data("state")
m <- merge(states, v, by="region")
m <- m[order(m$order),]
p<-qplot(long, lat, data=m, group=group, fill=ratio, geom="polygon")
I've tried the below and more:
cols <- c("8" = "red","4" = "blue","6" = "darkgreen", "10" = "orange")
p + scale_colour_manual(values = cols)
p + scale_colour_brewer(palette="Set1")
p + scale_color_manual(values=c("#CC6666", "#9999CC"))

The problem is that you are using a color scale but are using the fill aesthetic in the plot. You can use scale_fill_gradient() for two colors and scale_fill_gradient2() for three colors:
p + scale_fill_gradient(low = "pink", high = "green") #UGLY COLORS!!!
I was getting issues with scale_fill_brewer() complaining about a continuous variable supplied when a discrete variable was expected. One easy fix is to create discrete bins with cut() and then use that as the fill aesthetic:
m$breaks <- cut(m$ratio, 5) #Change to number of bins you want
p <- qplot(long, lat, data = m, group = group, fill = breaks, geom = "polygon")
p + scale_fill_brewer(palette = "Blues")

Related

How do I fill certain counties on a US map in R?

I am trying to construct a map of the eastern US with the counties lying in Appalachia highlighted as a certain color, while non-Appalachian counties are left white. I have constructed a county map of the eastern US using the following code:
library(usmap)
library(maps)
library(ggplot2)
us.counties = map_data('county')
head(us.counties)
#> long lat group order region subregion
#> 1 -86.50517 32.34920 1 1 alabama autauga
#> 2 -86.53382 32.35493 1 2 alabama autauga
#> 3 -86.54527 32.36639 1 3 alabama autauga
#> 4 -86.55673 32.37785 1 4 alabama autauga
#> 5 -86.57966 32.38357 1 5 alabama autauga
#> 6 -86.59111 32.37785 1 6 alabama autauga
plot_usmap("counties",
include = c(.east_north_central, .east_south_central, .south_atlantic,
.south_region, .northeast_region),
exclude = c('TX', 'AR', 'LA', 'OK'))
Which returned this map showing the eastern US with counties outlined.
I also have the following data frame appalachian.counties containing a list of all US counties in Appalachia by name and state they are in.
> head(appalachian.counties)
region subregion
1 alabama bibb
2 alabama blount
3 alabama calhoun
4 alabama chambers
5 alabama cherokee
6 alabama chilton
I would like to construct a map that looks like the blank map included above, but with the Appalachian counties included in the data frame appalachian.counties filled in a blue and the Appalachian counties specifically in Kentucky filled in red. Is this possible?
You could try this:
library(usmap)
library(maps)
us.counties = map_data('county')
states <- us.counties[us.counties$region %in% appalachian.counties$region,]
app <- us.counties[paste(us.counties$region, us.counties$subregion) %in%
paste(appalachian.counties$region, appalachian.counties$subregion),]
ken <- app[app$region == "kentucky",]
ggplot(states, aes(long, lat, group = group)) +
geom_polygon(fill = "white", colour = "gray75") +
geom_polygon(fill = "red", data = app, colour = "white") +
geom_polygon(fill = "blue", data = ken, colour = "white") +
coord_equal() +
theme_void()

Modify x axis label for each facet

I have this mosaic plot
I'd like to have only label on x-axis for individuals in correct facet.
for example you can see that in the last facet there are only 7 bars. i'd like to show only x axis labels for those 7 bars.
Hope i have been clear enough
here's my code and data
p<-ggplot(data = newdata) +
geom_mosaic(aes(weight = frequency, x = product(region),fill=factor(categ)),na.rm=TRUE) +facet_grid(~cutt) +theme(axis.text.x=element_text(angle=90, hjust= .1))+
guides(fill=guide_legend(title = "Type of Crime", reverse = TRUE))`
head(newdata)
region categ frequency median_income cutt vec
1 alabama burglary 0.25773 42917 39k-51k 0
2 alabama larceny 0.67646 42917 39k-51k 0
3 alabama motor_veichle_theft 0.06581 42917 39k-51k 0
4 arizona burglary 0.20239 50036 39k-51k 0
5 arizona larceny 0.71590 50036 39k-51k 0
6 arizona motor_veichle_theft 0.08171 50036 39k-51k 0

Maps, ggplot2, fill by state is missing certain areas on the map

I am working with maps and ggplot2 to visualize the number of certain crimes in each state for different years. The data set that I am working with was produced by the FBI and can be downloaded from their site or from here (if you don't want to download the dataset I don't blame you, but it is way too big to copy and paste into this question, and including a fraction of the data set wouldn't help, as there wouldn't be enough information to recreate the graph).
The problem is easier seen than described.
As you can see California is missing a large chunk as well as a few other states. Here is the code that produced this plot:
# load libraries
library(maps)
library(ggplot2)
# load data
fbi <- read.csv("http://www.hofroe.net/stat579/crimes-2012.csv")
fbi <- subset(fbi, state != "United States")
states <- map_data("state")
# merge data sets by region
fbi$region <- tolower(fbi$state)
fbimap <- merge(fbi, states, by="region")
# plot robbery numbers by state for year 2012
fbimap12 <- subset(fbimap, Year == 2012)
qplot(long, lat, geom="polygon", data=fbimap12,
facets=~Year, fill=Robbery, group=group)
This is what the states data looks like:
long lat group order region subregion
1 -87.46201 30.38968 1 1 alabama <NA>
2 -87.48493 30.37249 1 2 alabama <NA>
3 -87.52503 30.37249 1 3 alabama <NA>
4 -87.53076 30.33239 1 4 alabama <NA>
5 -87.57087 30.32665 1 5 alabama <NA>
6 -87.58806 30.32665 1 6 alabama <NA>
And this is what the fbi data looks like:
Year Population Violent Property Murder Forcible.Rape Robbery
1 1960 3266740 6097 33823 406 281 898
2 1961 3302000 5564 32541 427 252 630
3 1962 3358000 5283 35829 316 218 754
4 1963 3347000 6115 38521 340 192 828
5 1964 3407000 7260 46290 316 397 992
6 1965 3462000 6916 48215 395 367 992
Aggravated.Assault Burglary Larceny.Theft Vehicle.Theft abbr state region
1 4512 11626 19344 2853 AL Alabama alabama
2 4255 11205 18801 2535 AL Alabama alabama
3 3995 11722 21306 2801 AL Alabama alabama
4 4755 12614 22874 3033 AL Alabama alabama
5 5555 15898 26713 3679 AL Alabama alabama
6 5162 16398 28115 3702 AL Alabama alabama
I then merged the two sets along region. The subset I am trying to plot is
region Year Robbery long lat group
8283 alabama 2012 5020 -87.46201 30.38968 1
8284 alabama 2012 5020 -87.48493 30.37249 1
8285 alabama 2012 5020 -87.95475 30.24644 1
8286 alabama 2012 5020 -88.00632 30.24071 1
8287 alabama 2012 5020 -88.01778 30.25217 1
8288 alabama 2012 5020 -87.52503 30.37249 1
... ... ... ...
Any ideas on how I can create this plot without those ugly missing spots?
I played with your code. One thing I can tell is that when you used merge something happened. I drew states map using geom_path and confirmed that there were a couple of weird lines which do not exist in the original map data. I, then, further investigated this case by playing with merge and inner_join. merge and inner_join are doing the same job here. However, I found a difference. When I used merge, order changed; the numbers were not in the right sequence. This was not the case with inner_join. You will see a bit of data with California below. Your approach was right. But merge somehow did not work in your favour. I am not sure why the function changed order, though.
library(dplyr)
### Call US map polygon
states <- map_data("state")
### Get crime data
fbi <- read.csv("http://www.hofroe.net/stat579/crimes-2012.csv")
fbi <- subset(fbi, state != "United States")
fbi$state <- tolower(fbi$state)
### Check if both files have identical state names: The answer is NO
### states$region does not have Alaska, Hawaii, and Washington D.C.
### fbi$state does not have District of Columbia.
setdiff(fbi$state, states$region)
#[1] "alaska" "hawaii" "washington d. c."
setdiff(states$region, fbi$state)
#[1] "district of columbia"
### Select data for 2012 and choose two columns (i.e., state and Robbery)
fbi2 <- fbi %>%
filter(Year == 2012) %>%
select(state, Robbery)
Now I created two data frames with merge and inner_join.
### Create two data frames with merge and inner_join
ana <- merge(fbi2, states, by.x = "state", by.y = "region")
bob <- inner_join(fbi2, states, by = c("state" ="region"))
ana %>%
filter(state == "california") %>%
slice(1:5)
# state Robbery long lat group order subregion
#1 california 56521 -119.8685 38.90956 4 676 <NA>
#2 california 56521 -119.5706 38.69757 4 677 <NA>
#3 california 56521 -119.3299 38.53141 4 678 <NA>
#4 california 56521 -120.0060 42.00927 4 667 <NA>
#5 california 56521 -120.0060 41.20139 4 668 <NA>
bob %>%
filter(state == "california") %>%
slice(1:5)
# state Robbery long lat group order subregion
#1 california 56521 -120.0060 42.00927 4 667 <NA>
#2 california 56521 -120.0060 41.20139 4 668 <NA>
#3 california 56521 -120.0060 39.70024 4 669 <NA>
#4 california 56521 -119.9946 39.44241 4 670 <NA>
#5 california 56521 -120.0060 39.31636 4 671 <NA>
ggplot(data = bob, aes(x = long, y = lat, fill = Robbery, group = group)) +
geom_polygon()
The problem is in the order of arguments to merge
fbimap <- merge(fbi, states, by="region")
has the thematic data first and the geo data second. Switching the order with
fbimap <- merge(states, fbi, by="region")
the polygons should all close up.

Changing a continuous scale from decimal to percents

The scale for penetration is listed as a decimal (.5 and down), but I am having a problem changing it to a percent.
I tried to format it in my data as a percentage using this code
penetration_levels$Penetration<-sprintf("%.1f %%", 100*penetration_levels$Penetration)
which worked from a format sense, but when I tried to graph the plot I got an error saying penetration was used as a discrete, not continuous scale.
To fix that, used this code to format it as a numeric variable
penetration_levels$Penetration<-as.numeric(as.character(penetration_levels$Penetration))
Which returned a bunch of NAs. Does anyone know any other method of how I can change it to a percent?
Here is the code I used to map
ggplot code:
map <- ggplot(penetration_levels,aes(long,lat,group=region,fill=Penetration),) + geom_polygon() + coord _equal() + scale_fill_gradient2(low="red",mid="white",high="green",midpoint=.25)
map <- map + geom_point(data=mydata, aes(x=long, y=lat,group=1,fill=0, size=Annualized.Opportunity), color="gray6") + scale_size(name="Total Annual Opportunity-Millions",range=c(2,4))
map <- map + theme(plot.title = element_text(size = 12,face="bold"))
map
Head of mydata and penetration
head(mydata)
Sold.To.Customer City State Annualized.Opportunity location lat long
21 10000110 NEW YORK NY 12.142579 NEW YORK,NY 40.71435 -74.00597
262 10016487 FORT LAUDERDALE FL 12.087310 FORT LAUDERDALE,FL 26.12244 -80.13732
349 11001422 ALLEN PARK MI 10.910575 ALLEN PARK,MI 42.25754 -83.21104
19 10000096 ALTON IL 10.040067 ALTON,IL 38.89060 -90.18428
477 11067228 BAY CITY TX 10.030829 BAY CITY,TX 28.98276 -95.96940
230 10014909 BETHPAGE NY 9.320271 BETHPAGE,NY 40.74427 -73.48207
head(penetration_levels)
State region long lat group order subregion state To From Total Penetration
17 AL alabama -87.46201 30.38968 1 1 <NA> AL 10794947 12537359 23332307 0.462661
18 AL alabama -87.48493 30.37249 1 2 <NA> AL 10794947 12537359 23332307 0.462661
22 AL alabama -87.52503 30.37249 1 3 <NA> AL 10794947 12537359 23332307 0.462661
36 AL alabama -87.53076 30.33239 1 4 <NA> AL 10794947 12537359 23332307 0.462661
37 AL alabama -87.57087 30.32665 1 5 <NA> AL 10794947 12537359 23332307 0.462661
65 AL alabama -87.58806 30.32665 1 6 <NA> AL 10794947 12537359 23332307 0.462661
I also just noticed that there was a white strip, similar to a polygon that is missing in Washington… do you happen to know why that is? I tried to re-merge my data and order it again, but still the same result.
Any insight would be greatly appreciated.
Also, I noticed that Washington has a white polygon missing? Does anyone know why this happens?
You may load the scales package and use scale_fill_continuous(labels = percent). The percent argument is not very well documented in the argument section of the help text, but an example of this function, and other convenient formats from the scales package, can be found in the example section here.
A small example:
library(scales)
df <- data.frame(long = 1:10, lat = 1:10,
penetration = seq(from = 0.1, to = 1, by = 0.1))
ggplot(data = df, aes(x = long, y = lat, fill = penetration)) +
geom_point(shape = 21, size = 6) +
scale_fill_continuous(labels = percent)

Time Series in R with ggplot2

I'm a ggplot2 newbie and have a rather simple question regarding time-series plots.
I have a data set in which the data is structured as follows.
Area 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
MIDWEST 10 6 13 14 12 8 10 10 6 9
How do I generate a time series when the data is structured in this format.
With the reshape package, I could just alter the data to look like:
totmidc <- melt(totmidb, id="Area")
totmidc
Area variable value
1 MIDWEST 1998 10
2 MIDWEST 1999 6
3 MIDWEST 2000 13
4 MIDWEST 2001 14
5 MIDWEST 2002 12
6 MIDWEST 2003 8
7 MIDWEST 2004 10
8 MIDWEST 2005 10
9 MIDWEST 2006 6
10 MIDWEST 2007 9
Then run the following code to get the desired plot.
ggplot(totmidc, aes(Variable, Value)) + geom_line() + xlab("") + ylab("")
However, is it possible to generate a time series plot from the first
object in which the columns represent the years.
What is the error that ggplot2 gives you? The following seems to work on my machine:
Area <- as.numeric(unlist(strsplit("1998 1999 2000 2001 2002 2003 2004 2005 2006 2007", "\\s+")))
MIDWEST <-as.numeric(unlist(strsplit("10 6 13 14 12 8 10 10 6 9", "\\s+")))
qplot(Area, MIDWEST, geom = "line") + xlab("") + ylab("")
#Or in a dataframe
df <- data.frame(Area, MIDWEST)
qplot(Area, MIDWEST, data = df, geom = "line") + xlab("") + ylab("")
You may also want to check out the ggplot2 website for details on scale_date et al.
I am guessing that with "time series plot" you mean you want to get a bar chart instead of a line chart?
In that case, you have to modify your code only slightly to pass the correct parameters to geom_bar(). The geom_bar default stat is stat_bin, which will calculate a frequency count of your categories on the x-scale. With your data you want to override this behaviour and use stat_identity.
library(ggplot2)
# Recreate data
totmidc <- data.frame(
Area = rep("MIDWEST", 10),
variable = 1998:2007,
value = round(runif(10)*10+1)
)
# Line plot
ggplot(totmidc, aes(variable, value)) + geom_line() + xlab("") + ylab("")
# Bar plot
# Note that the parameter stat="identity" passed to geom_bar()
ggplot(totmidc, aes(x=variable, y=value)) + geom_bar(stat="identity") + xlab("") + ylab("")
This produces the following bar plot:

Resources