So, I have a dataset that has data for not only CONUS but also the island areas and Alaska. Now, I want to plot only the data for CONUS. I know I can subset it easily. But is there any easier way to that? Maybe an option in ggplot I don't know?
Here is the code:
ggplot() +
geom_polygon( data=usamap, aes(x=long, y=lat,group=group),colour="black", fill="white" )+
geom_point(data=df,aes(x=Longitude,y=Latitude))+
scale_colour_gradientn(name = "DL",colours = myPalette(10))+
xlab('Longitude')+
ylab('Latitude')+
coord_map(projection = "mercator")+
theme_bw()+
theme(legend.position = c(.93,.20),panel.grid.major = element_line(colour = "#808080"))+
ggsave("test.png",width=10, height=8,dpi=300)
Here is the dataset:
https://www.dropbox.com/s/k1z5uquhtc2b9nd/exported.csv?dl=0
You can do it and also use a decent projection at the same time:
library(ggplot2)
library(readr)
library(dplyr)
us <- map_data("state")
us <- fortify(us, region="region")
# for theme_map
devtools::source_gist("33baa3a79c5cfef0f6df")
# read your data and filter out points not in CONUS
read_csv("exported.csv") %>%
filter(Longitude>=-124.848974 & Longitude<=-66.885444,
Latitude>=24.396308 & Latitude<=49.384358) -> data
gg <- ggplot()
gg <- gg + geom_map(data=us, map=us,
aes(x=long, y=lat, map_id=region, group=group),
fill="#ffffff", color="#7f7f7f", size=0.25)
gg <- gg + geom_point(data=data,
aes(x=Longitude, y=Latitude),
color="#cb181d", size=1, alpha=1/10)
gg <- gg + coord_map("albers", lat0=39, lat1=45)
gg <- gg + theme_map()
gg
You have no aesthetic color mapping I can see, so your color scaling will have no impact. I used an alpha for overlapping/close points instead.
Looking at your reposted question, I think by far the best way is a simple subset. From this link, you can see the box around the continental USA is:
(-124.848974, 24.396308) - (-66.885444, 49.384358)
if you do a simple subset:
usamap<-usamap[usamap$Longitude > -124.848 &
usamap$Longitude < -66.886 &
usamap$Latitude > 24.3964 &
usamap$Latitude < 49.3844, ]
You will get your required points.
Since you said you'd be interested in a ggplot2 solution, you might consider modifying the arguments in coord_map(). For example:
coord_map(project = "globular",
xlim = c(-125, -66),
ylim = c(24, 50))
Of course, the "mercator" argument works, too!
Related
I'm creating a cloropleth map of the U.S where each county is colored by the proportion of the 2012 votes for Obama. I'd like to vary the opacity of county overlays by the population (similar to what was done here). I've tried adding alpha = populationVariable to my geom_map aes, but without luck.
Here is my current code. Can anyone point me in the right direction?
gg <- ggplot()
gg <- gg + geom_map(data=mapC, map=mapC, aes(x=long, y=lat, map_id=id, group=group, fill=mapC$proportionObama))
gg = gg+ scale_fill_gradient2(limits= c(0,100), name="Proportion of Votes for Obama", low="#E5000A", high="#0012BF",mid="#720964", midpoint=50)
gg = gg + theme_map() +coord_equal()
gg <- gg + geom_path(data = mapS, aes(long,lat, group=group), colour="gray50", size=.25)
gg = gg + theme(legend.position="right")
gg
I think that alpha needs to be a variable that's mapped to be between 0 and 1. The ggplot documentation always shows a fractional value.
Hue Scale - http://docs.ggplot2.org/0.9.3.1/scale_hue.html
Color Fill Alpha - http://docs.ggplot2.org/current/aes_colour_fill_alpha.html
You don't have reproducible code, so here was a quick test that seemed to work.
library(data.table)
library(ggplot2)
tmp = data.table(
'x'=c(1,2,3),
'y'=c(1,2,3),
'z'=c(.1,.5,.8)
)
p = ggplot()
p = p + geom_point( data=tmp , aes(x=x,y=y,alpha=z))
print(p)
I just had a play with ggplot2 in R, with syntax like
geom_map(data=world, map=world
aes(x=long, y=lat, map_id=region),
color="white", fill="#7f7f7f", size=0.05, alpha=1/4)
That gives me the world map, is it possible to only get UK map as background map?
Many thanks
Peddie
You can also do something like:
library(ggplot2)
library(ggthemes)
library(raster)
library(rgeos)
gbr <- getData("GADM", country="GBR", level=0)
gbr <- gSimplify(gbr, 0.01)
gbr_map <- fortify(gbr)
gg <- ggplot()
gg <- gg + geom_map(map=gbr_map, data=gbr_map,
aes(x=long, y=lat, map_id=id),
fill="#7f7f7f")
gg <- gg + coord_map()
gg <- gg + theme_map()
gg
Once my ggalt package is in CRAN you can even use a decent projection.
Also check out ggplot2::borders()
library(ggplot2)
ggplot() +
borders(reg="UK", color="white", fill="#7f7f7f", alpha=1/4)
The result should be equal to the one from #eipi10.
library(maps)
library(ggplot2)
dat=map_data("world")
ggplot() +
geom_map(data=dat[dat$region=="UK",], map=dat[dat$region=="UK",],
aes(x=long, y=lat, map_id=region),
color="white", fill="#7f7f7f", size=0.05, alpha=1/4) +
coord_fixed()
The library ggmap works very well with ggplot2.
You could try this:
library(ggmap)
#Google API
register_google(key = "your_api_key")
map <- get_map(location = 'UK', zoom = 6)
ggmap(map)
and add geom as you like.
This question already has answers here:
Force R to stop plotting abbreviated axis labels (scientific notation) - e.g. 1e+00
(9 answers)
Closed 8 months ago.
I am making a choropleth with ggplot and I am trying to fit the labels for my legend in the frame but R keeps putting the labeled values in scientific notation. Does anyone know of a way to address this? I have the following code which works fine when the values of my labels are smaller, but I need to include the range.
ta<- quantile(look13$capcpi,c(0, 0.2, 0.4, 0.6, 0.8, 1.0) )
t<- c('$35,141-$37,916', '$37,916-$40,236','$40,236-$43,364','$43,364-$45,280', '$45,280-$59,688')
look13$capcpi_q<- cut(look13$capcpi,ta, lables= t, include.lowest = TRUE)
lookmap<- merge(st,look13, by.x='id', by.y= 'area')
realpi<- ggplot(lookmap, aes(x=long, y=lat, group=group, fill= capcpi_q))+
geom_path() + geom_polygon(color='black')+
scale_fill_manual(values= pal)+ theme_clean()
Generally, you can use the scales package and a label parameter to scale_color_continuous (or discrete):
library(ggplot2)
library(scales)
library(ggthemes)
# make up some data
dat <- data.frame(state=tolower(rownames(USArrests)),
rate=USArrests$Murder*10000000,
stringsAsFactors=FALSE)
us <- map_data("state")
gg <- ggplot()
gg <- gg + geom_map(data=us, map=us,
aes(x=long, y=lat, map_id=region),
color="#7f7f7f", size=0.15, fill="white")
gg <- gg + geom_map(data=dat, map=us,
aes(fill=rate, map_id=state))
gg <- gg + scale_fill_continuous(label=comma)
gg <- gg + coord_map("albers", 39, 42)
gg <- gg + theme_map()
gg
I'm trying to plot a US map where each state is shaded by the count that it has. I've gotten the shading to work just fine. The problem I'm running into, however, is that the polygons look very jagged (I'm assuming something happened when I tried to merge the map_data('state') with my data frame of counts per state). My data frame before merging has 49 rows (Nevada was missing data in my set), and after merging has many more rows (expected for the long/lat items for the states) but the data appears to be copied correctly for each lat/long pair, so I'm unsure why the poly's are so jagged.
Code:
ggplot() +
geom_polygon(data=try1, aes(x=long, y=lat, group = group, fill= COUNT)) +
scale_fill_continuous(low='thistle2', high='darkred', guide='colorbar') +
theme_bw() + labs(fill="State Map Try Title1", title='Title2', x='', y='') +
scale_y_continuous(breaks=c()) +
scale_x_continuous(breaks=c()) +
theme(panel.border = element_blank())
Any help would be greatly appreciated (and obviously, if there is a better way to do it, I'm open to suggestions!).
You don't need to do the merge. You can use geom_map and keep the data separate from the shapes. Here's an example using the built-in USArrests data (reformatted with dplyr):
library(ggplot2)
library(dplyr)
us <- map_data("state")
arr <- USArrests %>%
add_rownames("region") %>%
mutate(region=tolower(region))
gg <- ggplot()
gg <- gg + geom_map(data=us, map=us,
aes(x=long, y=lat, map_id=region),
fill="#ffffff", color="#ffffff", size=0.15)
gg <- gg + geom_map(data=arr, map=us,
aes(fill=Murder, map_id=region),
color="#ffffff", size=0.15)
gg <- gg + scale_fill_continuous(low='thistle2', high='darkred',
guide='colorbar')
gg <- gg + labs(x=NULL, y=NULL)
gg <- gg + coord_map("albers", lat0 = 39, lat1 = 45)
gg <- gg + theme(panel.border = element_blank())
gg <- gg + theme(panel.background = element_blank())
gg <- gg + theme(axis.ticks = element_blank())
gg <- gg + theme(axis.text = element_blank())
gg
I encountered a similar problem when using ggplot2. As an alternative to #hrbrmstr 's solution, I found reloading the ggplot2 package (as well as rgdal/`maptools') resolved the issue for me.
I am wanting to add bathymetry lines to a map plot I am looking at. I am plotting points off the coast and we are interested as to how close to the continental shelf they are. I have seen a package called Marmap - but now I am using ggplot as it gives a higher resolution.
The code I've seen for getting bathymetry lines is this:
library(marmap)
Peru.bath <- getNOAA.bathy (lon1 = -90, lon2 = -70, lat1 = -20,
lat2 = -2, resolution = 10)
plot(Peru.bath)
The code I'm using which I want to add the bathymetry lines to is below:
coast_map <- fortify(map("worldHires", fill=TRUE, plot=FALSE))
gg <- ggplot()
gg <- gg + geom_map(data=coast_map, map=coast_map,
aes(x=long, y=lat, map_id=region),
fill="white", color="black") +
theme(panel.background = element_blank()) +
theme(panel.grid.major = element_blank()) +
theme(panel.grid.minor = element_blank()) +
theme(axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank())
gg <- gg + xlab("") + ylab("")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
aes(map_id=region), fill="gray")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg
Therefore I assumed it would be
gg <- gg + Peru.bath
However I am getting 'Error: Don't know how to add Peru.bath to a plot'
NB Just to make it clear, I do not have bathymetry data, I just wish to plot known shelf lines onto a map I have created, if that is possible.
I've just updated the development version of marmap on github. You can install it with:
library(devtools)
install_github("ericpante/marmap")
A function autoplot.bathy() for plotting bathy objects with ggplot2 is now included. Be sure to check it's help file and the examples to see what's possible. Here is an example with your dataset dat:
library(marmap) ; library(ggplot2)
dat <- getNOAA.bathy(-90,-70,-20,-2,res=4, keep=TRUE)
# Plot bathy object using custom ggplot2 functions
autoplot(dat, geom=c("r", "c"), colour="white", size=0.1) + scale_fill_etopo()
If you want to (i) add isobath lines to your map and (ii) determine the depth of your data points using get.depth() it would be much easier to stick with standard plots (marmap is designed to work with these). As a matter of fact, the "better resolution" you mention has nothing to do with base graphics nor ggplot2. In your example, the coastline you're plotting comes from the "worldHires" dataset from package mapdata and it has nothing to do with ggplot2. Indeed, you can add the same coastline on marmap plots.
Here is some code to produce two more than decent maps using base graphics and marmap:
library(marmap) ; library(mapdata)
# Get bathymetric data
dat <- getNOAA.bathy(-90,-70,-20,-2,res=4, keep=TRUE)
# Create nice color palettes
blues <- c("lightsteelblue4", "lightsteelblue3", "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))
## First option for plotting
plot(dat, land=TRUE, n=100, lwd=0.03)
map("worldHires", res=0, add=TRUE)
# Second option
plot(dat, im=TRUE, land=TRUE, bpal=list(c(min(dat),0,blues),c(0,max(dat),greys)), lwd=.05, las=1 )
map("worldHires", res=0, lwd=0.7, add=TRUE)
# Add -200m and -1000m isobath
plot(dat, deep=-200, shallow=-200, step=0, lwd=0.5, drawlabel=TRUE, add=TRUE)
plot(dat, deep=-1000, shallow=-1000, step=0, lwd=0.3, drawlabel=TRUE, add=TRUE)
Note that the resolution used here is not the highest possible. the res argument of getNOAA.bathy() is set to 4 here. This downloads a 2.7Mb dataset that can be saved locally by setting the keep argument to TRUE. The highest resolution possible would be res=1, but in my opinion, it is overkill for such a wide geographical scale. This code produces the 2 plots below:
Running a bit short on time this morning, but this should help you get started (and, can no doubt be improved by other R geo folks:
library(maps)
library(mapdata)
library(ggplot2)
library(marmap)
library(Grid2Polygons)
coast_map <- fortify(map("worldHires", fill = TRUE, plot = FALSE))
Peru.bath <- getNOAA.bathy (lon1 = -90, lon2 = -70, lat1 = -20,
lat2 = -2, resolution = 10)
peru_bathy_df <- Grid2Polygons(as.SpatialGridDataFrame(Peru.bath),
level=TRUE, pretty=TRUE)
peru_bathy_map <- fortify(peru_bathy_df)
gg <- ggplot()
gg <- gg + geom_map(data=peru_bathy_map, map=peru_bathy_map,
aes(map_id=id), color="black", fill="white")
gg <- gg + geom_map(data=coast_map, map=coast_map,
aes(x=long, y=lat, map_id=region),
fill="white", color="black")
gg <- gg + geom_map(data=data.frame(region="Peru"), map=coast_map,
aes(map_id=region), fill="steelblue")
gg <- gg + xlim(-90,-70) + ylim(-20,-2)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg
Obviously you want a better picture than that, but the basic idea is to get it converted into an object that ggplot can handle (so, a SpatialPolygonsDataFrame). Lots of good non-ggplot examples in the bathy and Grid2Polygons help.
NOTE: these take some time to convert/render and the bathy examples do show a way to do this without ggplot that will be much faster.