removing scientific notation from a ggplot map legend [duplicate] - r

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

Related

How to flip y axis in geom_sf()?

Trying to combine a geom_sf() with some other geoms. I need to reverse the y-axis for the plot to appear correctly. However, geom_sf() seems to ignore scale_y_reverse().
Example:
# install the dev version of ggplot2
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
library(sf)
library(rgeos)
library(sp)
# make triangle
tmpdf <- data.frame(id = 1,
geom = c("LINESTRING(10 10,-10 10,0 0,10 10)"), stringsAsFactors = F)
# read WKT polygons into 'sp' SpatialPolygons object
tmpdf$spgeom <- lapply(tmpdf$geom, FUN = function(x) readWKT(x))
# extract coordinates from the linestring (there has got to be a better way to do this...)
test <- tmpdf[1,"spgeom"]
test2 <- sapply(test, FUN=function(x) x#lines)
test3 <- sapply(test2, FUN=function(x) x#Lines)
test4 <- lapply(test3, FUN=function(x) x#coords)
# plot the sp coordinates
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed()
# make an 'sf' sfc_POLYGON object
tmpdf$sfgeom <- st_as_sfc(tmpdf$geom)
## plot both together, they overlap
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red")
plot outputs with warning:
Coordinate system already present. Adding new coordinate system, which
will replace the existing one.
## plot with scale reverse, and everything but the geom_sf flips.
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red") +
scale_y_reverse()
plot outputs with warning:
Coordinate system already present. Adding new coordinate system, which
will replace the existing one.
Suggestions for getting the geom_sf y coordinates reversed?
I tried this:
coord_sf(ylim=-(range(st_coordinates(tmpdf$sfgeom)[,"Y"])))
and all that did was change the axis, not the actual geoms.
Aha! Here's a workaround:
## get the geom coordinates as data.frame
geomdf <- st_coordinates(tmpdf$sfgeom)
## reverse Y coords
geomdf[,"Y"] <- geomdf[,"Y"]*-1
## re-create geom
tmpdf$sfgeom2 <- st_as_sfc(st_as_text(st_linestring(geomdf)))
## plot the reversed y-coordinate geom:
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom2), color="red") +
scale_y_reverse()

ggplot alter map fill opacity by second variable

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)

Plot the intensity of a continuous with geom_tile in ggplot

I'm trying to plot a continuous variable on space. I saw this example that gets the same result that I need:
library("MASS")
library("ggplot2")
library(reshape2)
DB<-melt(volcano)
ggplot(DB, aes(x=Var1, y=Var2, fill=value)) +geom_tile()
So I did with my data:
library(repmis)
url<-"https://www.dropbox.com/s/4m5qk32wjgrjq40/dato.RDATA"
source_data(url)
library(ggplot2)
ggplot(dato,aes(y=variable,x=y,fill=value))+geom_tile()
That's wonderful. But my "x" and "y" are kilometers distance (east and north) from a point in space. I transformed these in latitude and longitude. But now my plot doesn't work!
ggplot(dato,aes(y=lat,x=long,fill=value))+geom_tile()
I don't understand why. Anyway plotting my data like points the result is very similar:
ggplot(dato,aes(y=lat,x=long,fill=value))+geom_point()
ggplot(dato,aes(y=variable,x=y,fill=value))+geom_point()
You can cheat a bit and use geom_point with a square shape:
#devtools::install_github("sjmgarnier/viridis")
library(viridis)
library(ggplot2)
library(ggthemes)
library(scales)
library(grid)
gg <- ggplot(dato)
gg <- gg + geom_point(aes(x=long, y=lat, color=value), shape=15, size=5)
gg <- gg + coord_equal()
gg <- gg + scale_color_viridis(na.value="#FFFFFF00")
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg
I did not project the lat/long pairs and just used coord_equal. You should use a proper projection for the region being mapped.
And, now you have me curious as to what those hot spots are around Milan :-)
gmap <- get_map(location=c(9.051062, 45.38804, 9.277473, 45.53438),
source="stamen", maptype="toner", crop=TRUE)
gg <- ggmap(gmap)
gg <- gg + geom_point(data=dato, aes(x=long, y=lat, color=value), shape=15, size=5, alpha=0.25)
gg <- gg + coord_map()
gg <- gg + scale_color_viridis(na.value="#FFFFFF00")
gg <- gg + theme_map()
gg <- gg + theme(legend.position="right")
gg

How can I only plot a CONUS map in ggplot2?

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!

ggplot US state map; colors are fine, polygons jagged - r

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.

Resources