I'm trying to use geom_path and geom_text to create a labeled map, but it is not going well. I can use each geom_path and geom_text separately, but I can't seem to get them to work together. I think it has something to do with geom_polygon, but I'm not sure what.
Here is how I prepared my shapefile for mapping:
meck.hiv <- as(meck.hiv, "Spatial")
meck.hiv#data$seq_id <- seq(1:nrow(meck.hiv#data)) #create unique id for each polygon
meck.hiv#data$id <- rownames(meck.hiv#data)
meck.hivdf <- fortify(meck.hiv) #fortify the data
zipcodedf <- merge(meck.hivdf, meck.hiv#data,
by = "id")# merge the "fortified" data with the data from our spatial object
cnames <- aggregate(cbind(long, lat) ~ zip, data=zipcodedf, FUN=function(x)mean(range(x))) #get the names of our zipcode (and center the coordinates for labels)
With this, I was able to get the following maps:
With labels, no paths:
p2 <- ggplot(data = zipcodedf, aes(x = long, y = lat)) +
geom_polygon(aes(group=group, fill=hispanic.dis)) +
geom_text(data=cnames, aes(long, lat, label = zip), size=3, fontface='bold', color="black")+ #This put in zip code names
scale_fill_brewer(breaks=c(1, 2, 3, 4, 5, 6, 7), labels=c("<5", "5-10", "11-15", "16-20", "21-25", "26-30", "31+"), palette="Reds",
na.value="darkgrey") +
coord_equal() +
theme(panel.background= element_rect(color="black")) +
theme(axis.title = element_blank(), axis.text = element_blank()) +
labs(title = "Hispanic Population by Zip Code", fill="Hispanic Population (% of Total)")
Resulting map with labels but no path
Paths, but no labels:
p3 <- ggplot(data = zipcodedf, aes(x = long, y = lat, group = group, fill = hispanic.dis)) +
geom_polygon() +
geom_path(color = "black", size = 0.2)+ #Oddly, use of geom_path with the above leads to weird stuff, but we can customize map lines without labels here
scale_fill_brewer(breaks=c(1, 2, 3, 4, 5, 6, 7), labels=c("<5", "5-10", "11-15", "16-20", "21-25", "26-30", "31+"), palette="Reds",
na.value="darkgrey") +
coord_equal() +
theme(panel.background=element_blank())+
theme(panel.background= element_rect(color="black")) +
theme(axis.title = element_blank(), axis.text = element_blank()) +
labs(title = "Hispanic Population by Zip Code", fill="Hispanic Population(% of Total)")
Resulting path with paths but no labels
Trying to combine
p4 <- ggplot(data = zipcodedf, aes(x = long, y = lat)) +
geom_polygon(aes(group=group, fill=hispanic.dis)) +
geom_text(data=cnames, aes(long, lat, label = zip), size=3, fontface='bold', color="black")+
geom_path(color = "black", size = 0.2)+ #Oddly, use of geom_path with the above leads to weird stuff, but we can customize map lines without labels here
scale_fill_brewer(breaks=c(1, 2, 3, 4, 5, 6, 7), labels=c("<5", "5-10", "11-15", "16-20", "21-25", "26-30", "31+"), palette="Reds",
na.value="darkgrey") +
coord_equal() +
theme(panel.background=element_blank())+
theme(panel.background= element_rect(color="black")) +
theme(axis.title = element_blank(), axis.text = element_blank()) +
labs(title = "Hispanic Population by Zip Code", fill="Hispanic Population(% of Total)")
Resulting screwed up plot with paths and labels
My trouble-shooting suggests that there's something about how geom_path is interacting with geom_polygon combined with ggplot(), but if I move all the instructions into geom_polygon, path doesn't show up at all (although a plot will generate), and if I move all the instructions into ggplot(), I get an error: "Error in FUN(X[[i]], ...): object 'group' not found" (below).
p5 <- ggplot(data = zipcodedf, aes(x = long, y = lat, group = group, fill = hispanic.dis)) +
geom_polygon() +
geom_path(color = "black", size = 0.2)+
geom_text(data=cnames, mapping=aes(x=long, y=lat))+#Oddly, use of geom_path with the above leads to weird stuff, but we can customize map lines without labels here
scale_fill_brewer(breaks=c(1, 2, 3, 4, 5, 6, 7), labels=c("<5", "5-10", "11-15", "16-20", "21-25", "26-30", "31+"), palette="Reds",
na.value="darkgrey") +
coord_equal() +
theme(panel.background=element_blank())+
theme(panel.background= element_rect(color="black")) +
theme(axis.title = element_blank(), axis.text = element_blank()) +
labs(title = "Hispanic Population by Zip Code", fill="Hispanic Population(% of Total)")
Any help is appreciated. Please let me know if I need to provide more information on anything.
{ggplot2}'s layering and inheritance can be confusing at times. I hope the following helps. Also check out whether you really want an "additional" geom_path() layer. It feels like you want to depict/highlight the county boundaries. Please also note the use of color for setting the boundary(line) color for a layer in the example.
I have to emulate your problem, as you did not provide a reproducible example. The initial code is to get me the map data for North Carolina. I construct a cnames dataframe for the county names. You should be able to apply this to your zip-code problem at the county level ... :)
library(dplyr)
library(ggplot)
library(maps) # helper package to get some map data
library(mapdata) # helper for some map data
counties <- map_data("county") %>% filter(region == "north carolina")
head(counties)
yields a data frame
long lat group order region subregion
1 -79.53800 35.84424 1857 54915 north carolina alamance
2 -79.54372 35.89008 1857 54916 north carolina alamance
3 -79.53800 35.98175 1857 54917 north carolina alamance
4 -79.52081 36.23385 1857 54918 north carolina alamance
5 -79.26298 36.23385 1857 54919 north carolina alamance
6 -79.27444 35.90726 1857 54920 north carolina alamance
Plotting the counties only (note: this would be your zip-code level).
To explain the principle of layer inheritance, I "set" all parameters in the layer call (i.e. geom_polygon()):
ggplot() +
geom_polygon(data = counties
, aes(x = long, y = lat, group = group) # aesthetic mapping
, color = "white" # fixed value for "line"
, fill = "lightblue") # fixed value for "fill"
If you now would add the geom_path() layer without giving it aesthetics, the plot will not change. Check that I set the color to blue and the linesize to 2 for demo purposes.
ggplot() +
geom_polygon(data = counties, aes(x = long, y = lat, group = group), colour = "white", fill = "lightblue") +
# ---------------- adding a layer with no aesthetics -----------
geom_path(color = "blue", size = 2) # ... no joy!
If you now move the data and aesthetics to ggplot() "base"-layer, also path will inherit the aesthetics. In this case path will draw the "outlines" of the of the grouped lat/lon positions. The layer order and color/size of geom_path() will "overwrite" the white coloured polygon lines.
ggplot(data = counties, aes(x = long, y = lat, group = group)) +
geom_polygon( colour = "white", fill = "lightblue") +
#------------ path layer with inherited "polygon" grouping
geom_path(color = "blue", size = 2)
Next let's create the (zipcodes :) ) aka text labels by averaging the lat/lon values for the different polygon segment points.
cnames <- counties %>%
group_by(subregion) %>%
summarise(long = mean(long), lat = mean(lat) # averaging for "mid"-point
)
> cnames
# A tibble: 100 x 3
subregion long lat
<chr> <dbl> <dbl>
1 alamance -79.4 36.0
2 alexander -81.2 35.9
3 alleghany -81.1 36.5
Now add a geom_text() layer to show the (zip codes) aka subregion names.
ggplot(data = counties, aes(x = long, y = lat, group = group)) +
geom_polygon( colour = "white", fill = "lightblue") +
geom_path(color = "blue", size = 2) +
# --------------- adding a geom_text() layer
geom_text(data = cnames, aes(x = long, y = lat), color = "green")
## ------- uuummmppfff throws an error
Error in FUN(X[[i]], ...) : object 'group' not found
This throws an error. So why is that? Implicitly the group aesthetic in the ggplot() call is understood by geom_polygon() and geom_path() ... however geom_text() has issues with.
Moving the group aesthetics to the polygon layer ...
ggplot(data = counties, aes(x = long, y = lat)) +
geom_polygon( aes(group=group), colour = "white", fill = "lightblue") +
geom_path(color = "blue", size = 2) +
geom_text(data = cnames, aes(x = long, y = lat, label = "subregion"), color = "green")
does the trick but corrupts the geom_path() layer.
What happens here is that the data points (i.e. lat/lon) are no longer grouped, and ggplot connects the end points in the order they appear in the counties data frame. These are the jig-jag lines you see across your plot.
Accordingly, you would need to put another aes(group=group) for the geom_path layer! ... assuming you really want the path for the outlines.
ggplot(data = counties, aes(x = long, y = lat)) +
geom_polygon( aes(group=group), colour = "white", fill = "lightblue") +
geom_path(aes(group=group), color = "blue", size = 2) +
geom_text(data = cnames, aes(x = long, y = lat, label = "subregion"), color = "green")
Obviously the color = "white" is overwritten by the geom_path() call. You may skip one or the other.
As a rule of thumb, ggplot works well with "long" data tables. The moment you add a 2nd (or more other data objects) make sure to track which aesthetics are required and/or inherited from one layer to the other. In your original example, you could move the geom_path() upwards to have the group = group aesthetics from the geom_polygon() call.
In case of doubt, always populate the data = ... and aes() for each layer before combining (and inheriting) parameters across layers.
Good luck!
Related
Using this dataset: https://www.kaggle.com/datasets/syuzai/perth-house-prices. Is there a way of prettying it up (besides changing the colour scale) by turning it into a choropleth? Each individual point represents the price of a single house; the original data does organise the house prices by suburb level but the ozmaps package only gives boundaries up to LGA/district level.
library(ozmaps)
library(sf)
library(ggplot2)
ozmaps <- ozmaps::ozmap_states
p<- ggplot(ozmaps) +
geom_sf() +
geom_point(data = PerthReg2005, aes(x = LONGITUDE, y = LATITUDE, colour = PRICE),
size = 1, shape = 23,) +
coord_sf(xlim = c(115.5827,116.3432), ylim = c(-31.45745,-32.47298))
p + scale_colour_gradientn(colours = terrain.colors(10))
I am trying to label my polygons by using ggplot in R. I found a topic here on stackoverflow that I think is very close to what I want except with points.
Label points in geom_point
I found some methods online. Now I first need to find the central location of each shape and then I have to put these locations together with the name together. Then link this to the labeling function in geom_text()
ggplot centered names on a map
Since I have been trying for a long time now I decided to ask the question and hope that someone here can give me the final push to what I want. My plotting function:
region_of_interest.fort <- fortify(region_of_interest, region = "score")
region_of_interest.fort$id <- as.numeric(region_of_interest.fort$id)
region_of_interest.fort$id <- region_of_interest.fort$id
region_of_interest.fort1 <- fortify(region_of_interest, region = "GM_NAAM")
region_of_interest.fort1$id <- as.character(region_of_interest.fort1$id)
region_of_interest.fort1$id <- region_of_interest.fort1$id
idList <- unique(region_of_interest.fort1$id)
centroids.df <- as.data.frame(coordinates(region_of_interest))
names(centroids.df) <- c("Longitude", "Latitude")
randomMap.df <- data.frame(id = idList, shading = runif(length(idList)), centroids.df)
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
It gives me the error: ggplot2 doesn't know how to deal with data of class uneval
My data
region_of_interest$GM_NAAM
[1] Groningen Haren Ooststellingwerf Assen Aa en Hunze Borger- Odoorn
[7] Noordenveld Westerveld Tynaarlo Midden-Drenthe
415 Levels: 's-Gravenhage 's-Hertogenbosch Aa en Hunze Aalburg Aalsmeer Aalten ... Zwolle
region_of_interest$score
[1] 10 -2 -1 2 -1 -4 -4 -5 0 0
Try something like this?
Get a data frame of the centroids of your polygons from the
original map object.
In the data frame you are plotting, ensure there are columns for
the ID you want to label, and the longitude and latitude of those
centroids.
Use geom_text in ggplot to add the labels.
Based on this example I read a world map, extracting the ISO3 IDs to use as my polygon labels, and make a data frame of countries' ID, population, and longitude and latitude of centroids. I then plot the population data on a world map and add labels at the centroids.
library(rgdal) # used to read world map data
library(rgeos) # to fortify without needing gpclib
library(maptools)
library(ggplot2)
library(scales) # for formatting ggplot scales with commas
# Data from http://thematicmapping.org/downloads/world_borders.php.
# Direct link: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip
# Unpack and put the files in a dir 'data'
worldMap <- readOGR(dsn="data", layer="TM_WORLD_BORDERS_SIMPL-0.3")
# Change "data" to your path in the above!
worldMap.fort <- fortify(world.map, region = "ISO3")
# Fortifying a map makes the data frame ggplot uses to draw the map outlines.
# "region" or "id" identifies those polygons, and links them to your data.
# Look at head(worldMap#data) to see other choices for id.
# Your data frame needs a column with matching ids to set as the map_id aesthetic in ggplot.
idList <- worldMap#data$ISO3
# "coordinates" extracts centroids of the polygons, in the order listed at worldMap#data
centroids.df <- as.data.frame(coordinates(worldMap))
names(centroids.df) <- c("Longitude", "Latitude") #more sensible column names
# This shapefile contained population data, let's plot it.
popList <- worldMap#data$POP2005
pop.df <- data.frame(id = idList, population = popList, centroids.df)
ggplot(pop.df, aes(map_id = id)) + #"id" is col in your df, not in the map object
geom_map(aes(fill = population), colour= "grey", map = worldMap.fort) +
expand_limits(x = worldMap.fort$long, y = worldMap.fort$lat) +
scale_fill_gradient(high = "red", low = "white", guide = "colorbar", labels = comma) +
geom_text(aes(label = id, x = Longitude, y = Latitude)) + #add labels at centroids
coord_equal(xlim = c(-90,-30), ylim = c(-60, 20)) + #let's view South America
labs(x = "Longitude", y = "Latitude", title = "World Population") +
theme_bw()
Minor technical note: actually coordinates in the sp package doesn't quite find the centroid, but it should usually give a sensible location for a label. Use gCentroid in the rgeos package if you want to label at the true centroid in more complex situations like non-contiguous shapes.
The accepted answer here may work, but the actual question asked specifically notes that there is an error "ggplot2 doesn't know how to deal with data of class uneval."
The reason that it is giving you the error is because the inclusion of centroids.df needs to be a named variable (e.g. accompanied by "data=")
Currently:
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
Should be (note: "data=centroids.df"):
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(data=centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
This issue was addressed here: How to deal with "data of class uneval" error from ggplot2?
I've been plotting two sets of positional data with geom_point from different data sets (MR + MRTag).
MR
detect_date Latitude Longitude species
12/04/2016 11:08 -6.6524 71.3475 Manta Ray
12/04/2016 11:09 -6.6524 71.3475 Manta Ray
12/04/2016 11:10 -6.6524 71.3475 Manta Ray
16/04/2016 21:27 -6.6524 71.3475 Manta Ray
MRTag
species taggingdate deploy_lat deploy_lon
Manta Ray 3/24/2016 -5.4191 71.83855
Manta Ray 02/05/2013 -5.2568 71.65768333
Manta Ray 02/07/2013 -5.33448 71.9812
Manta Ray 02/08/2013 -5.3046 71.94231667
I then used the code below to make a base map
library(ggmap)
MR_bbox <- make_bbox(lon = MR$Longitude, lat = MR$Latitude, f=1)
MR_map <- get_map(location = MR_bbox, source = "google", maptype = "satellite")
Then plotted my location data from Mr + MRTag onto the map
MR_plot <-
ggmap(MR_map) +
geom_point(data = MR, mapping = aes(x = Longitude, y = Latitude),
shape = 1, color = "white") +
geom_point(data = MRTag, mapping = aes(x = deploy_lon, y = deploy_lat),
shape = 25, fill = "#00FF00", color = "#00FF00") +
xlab("Longitude") +
ylab("Latitude")
This gave me this plot
I'd like to add a legend for the two shapes to the map but I'm not sure of the best way to do it, and methods so far haven't worked
The solution is actually really simple: just move the relevant aesthetic arguments into the aes().
MR_plot <- ggmap(MR_map) +
geom_point(data = MR, aes(x = Longitude, y = Latitude,
color = 'detect', shape = 'detect', fill = 'detect')) +
geom_point(data = MRTag, aes(x = deploy_lon, y = deploy_lat,
color = 'tag', shape = 'tag', fill = 'tag')) +
xlab("Longitude") +
ylab("Latitude") +
scale_color_manual(name = 'legend', values = c(detect = 'white', tag = '#00FF00')) +
scale_fill_manual(name = 'legend', values = c(detect = NA, tag = '#00FF00')) +
scale_shape_manual(name = 'legend', values = c(detect = 1, tag = 25))
It's actually slightly confusing: if you use color= outside the aes(), then you set the actual color of those points and there is no legend because it's purely an aesthetic choice.
If you use color= (or fill= or shape=) inside the aes(), however, what you're doing is defining another variable that controls the color of the points. If you wanted to color those points based on species, for example, your aes() would be: aes(x = Longitude, y = Latitude, color = species). This is same thing: except by passing a single string you set the color variable for all points in that geom_point to a single value.
You then have to use a scale_color_* function (and corresponding functions for fill and shape) to set those color variables to the specific colors you want. By default, each scale defined in the aes() will get it's own legend. But if you name the legends and give them the same name, then they will be combined into one.
Okay so here is my code for a base map:
gg <- ggmap(Peru) +
geom_map(data = peru.coast, map = peru.coast, aes(x = long, y = lat, map_id = region),
fill="gray", color="black") +
xlim(-86, -70) +
ylim(-20, -4) +
labs(x = "Longitude", y = "Latitude") +
coord_map()
I then add in towns I wish to name manually (wasn't sure how to do it using google maps as I only wanted these 4)
gg <- gg + geom_point(aes(x=-78.981885, y=-8.229354, size=3)) +
annotate("text", label='Salaverry', size=4, x=-77.2, y=-8.229354) +
geom_point(aes(x=-71.345838, y=-17.644347, size=3)) +
annotate("text", x=-70.545838, y=-17.644347, label = 'Ilo', size=4) +
geom_point(aes(x=-77.142375, y=-12.047544, size=3)) +
annotate("text", x=-75.9, y=-12.047544, label = 'Callao', size=4) +
geom_point(aes(x=-78.610677, y=-9.074166, size=3)) +
annotate("text", x=-76.9, y=-9.074166, label = 'Chimbote', size=4)
gg <- gg + guides(size=FALSE) #this removes the legend with the black dot and '3' on it
gg
I get this lovely map:
I then use this dataset to add datapoints, and I wish to make the points bigger or smaller according to 'n' abundance
Trip_Set sex Set.Lon Set.Lat n
119_1 hembra -81.09390 -9.32338 2
119_7 hembra -81.03117 -9.09622 1
161_3 macho -83.76533 -9.74533 5
193_8 hembra -81.00888 -9.00950 7
255_5 macho -80.14992 -8.64592 1
271_6 hembra -72.20233 -18.05117 6
271_6 macho -72.20233 -18.05117 7
328_7 hembra -78.66667 -12.91700 2
403_3 hembra -80.03037 -10.03900 1
428_2 hembra -83.01305 -8.74883 2
655_4 hembra -71.58363 -18.24882 1
using this code:
ggAB <- gg + geom_point(data=dframe4, aes(Set.Lon, Set.Lat, colour='red', size=n))
ggAB <- ggAB + theme(legend.title = element_text(colour="black", size=12, face="bold"))
ggAB <- ggAB + guides(colour=FALSE) #This removes the legend for the red colour
ggAB <- ggAB + scale_size(name='Sharks per line', range = c(5,9))
ggAB <- ggAB + theme(legend.key=element_rect(fill = NA)) #This removes the boxes around the points
ggAB
However, when I do this... I get this:
The datapoints are plotted great (phew!), but why does it make the points bigger for my town names? I can't seem to get it to just keep the abundance for my 'n' number datapoints... It also doesn't put an automatic legend on (as ggplot usually does), even when I try and put one in manually using the scale_discrete function.
I thought it might be something to do with the fact that I use gg + guides(size=FALSE) in the first part, but even when taking that out it doesn't work, but adds in an annoying legend for my town datapoints.
Any ideas?
The problem is that in the code where you add the towns, you have put the size inside the aes. Therefore it also gets transformed when you call scale_size(name='Sharks per line', range = c(5,9)). Just use size outside the aes:
gg <- gg + geom_point(aes(x=-78.981885, y=-8.229354), size=3) +
annotate("text", label='Salaverry', size=4, x=-77.2, y=-8.229354) +
geom_point(aes(x=-71.345838, y=-17.644347), size=3) +
annotate("text", x=-70.545838, y=-17.644347, label = 'Ilo', size=4) +
geom_point(aes(x=-77.142375, y=-12.047544), size=3) +
annotate("text", x=-75.9, y=-12.047544, label = 'Callao', size=4) +
geom_point(aes(x=-78.610677, y=-9.074166), size=3) +
annotate("text", x=-76.9, y=-9.074166, label = 'Chimbote', size=4)
In addition to #shadow's answer, I'd like to leave the following for the OP as supplementary information. This comes from the chat with the OP. If you want to avoid using annotate, you can use geocode in the ggmap package. Here, I added some from my answer to the previous question of the OP, and I combined/modified the OP's code. One change is that I used alpha so that you can see red/pink points in the ocean. One note is that the positions of the city names are not perfect; the further you go down south in the map, the more you see gaps between points and city names. This could be due to something to do with map projection. According to Wiki, googlemap is using something close to marcator, but not exact the same. This could be the reason. Some GIS experts here would be able to provide more information.
library(ggmap)
library(mapdata)
library(ggplot2)
# Get Peru map
Peru <- get_map(location = "Peru", zoom = 5, maptype="satellite")
# This is the layer I wish to put over the top
coast_map <- fortify(map("worldHires", fill = TRUE, plot = FALSE))
# Subset data for Peru
peru.coast <- subset(coast_map, region == "Peru")
### Get lon and lat using geocode() in the ggmap package and crate a data frame
cities <- c("Salaverry", "Chimbote", "Callao", "Ilo")
locations <- geocode(cities)
locations$city <- cities
locations2 <- transform(locations, lon2 = lon + 1.1) # This is for text position
ggmap(Peru) +
geom_map(data = peru.coast, map = peru.coast, aes(x = long, y = lat, map_id = region),
fill="gray", color="black") +
geom_point(data = locations2, aes(x = lon, y = lat, color = city), size = 4) +
geom_text(data = locations2, aes(x = lon2, y = lat, label = city), size = 3) +
scale_color_manual(values = rep(c("black"), times = 4)) +
geom_point(data = newdata, aes(Set.Lon, Set.Lat, size = n), colour = "red", alpha = 0.5) +
scale_size(name = "Sharks per line", range = c(5,9)) +
xlim(-86, -70) +
ylim(-20, -4) +
labs(x = "Longitude", y = "Latitude") +
coord_map("mercator") +
guides(colour=FALSE) +
theme(legend.key=element_rect(fill = NA))
I am trying to label my polygons by using ggplot in R. I found a topic here on stackoverflow that I think is very close to what I want except with points.
Label points in geom_point
I found some methods online. Now I first need to find the central location of each shape and then I have to put these locations together with the name together. Then link this to the labeling function in geom_text()
ggplot centered names on a map
Since I have been trying for a long time now I decided to ask the question and hope that someone here can give me the final push to what I want. My plotting function:
region_of_interest.fort <- fortify(region_of_interest, region = "score")
region_of_interest.fort$id <- as.numeric(region_of_interest.fort$id)
region_of_interest.fort$id <- region_of_interest.fort$id
region_of_interest.fort1 <- fortify(region_of_interest, region = "GM_NAAM")
region_of_interest.fort1$id <- as.character(region_of_interest.fort1$id)
region_of_interest.fort1$id <- region_of_interest.fort1$id
idList <- unique(region_of_interest.fort1$id)
centroids.df <- as.data.frame(coordinates(region_of_interest))
names(centroids.df) <- c("Longitude", "Latitude")
randomMap.df <- data.frame(id = idList, shading = runif(length(idList)), centroids.df)
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
It gives me the error: ggplot2 doesn't know how to deal with data of class uneval
My data
region_of_interest$GM_NAAM
[1] Groningen Haren Ooststellingwerf Assen Aa en Hunze Borger- Odoorn
[7] Noordenveld Westerveld Tynaarlo Midden-Drenthe
415 Levels: 's-Gravenhage 's-Hertogenbosch Aa en Hunze Aalburg Aalsmeer Aalten ... Zwolle
region_of_interest$score
[1] 10 -2 -1 2 -1 -4 -4 -5 0 0
Try something like this?
Get a data frame of the centroids of your polygons from the
original map object.
In the data frame you are plotting, ensure there are columns for
the ID you want to label, and the longitude and latitude of those
centroids.
Use geom_text in ggplot to add the labels.
Based on this example I read a world map, extracting the ISO3 IDs to use as my polygon labels, and make a data frame of countries' ID, population, and longitude and latitude of centroids. I then plot the population data on a world map and add labels at the centroids.
library(rgdal) # used to read world map data
library(rgeos) # to fortify without needing gpclib
library(maptools)
library(ggplot2)
library(scales) # for formatting ggplot scales with commas
# Data from http://thematicmapping.org/downloads/world_borders.php.
# Direct link: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip
# Unpack and put the files in a dir 'data'
worldMap <- readOGR(dsn="data", layer="TM_WORLD_BORDERS_SIMPL-0.3")
# Change "data" to your path in the above!
worldMap.fort <- fortify(world.map, region = "ISO3")
# Fortifying a map makes the data frame ggplot uses to draw the map outlines.
# "region" or "id" identifies those polygons, and links them to your data.
# Look at head(worldMap#data) to see other choices for id.
# Your data frame needs a column with matching ids to set as the map_id aesthetic in ggplot.
idList <- worldMap#data$ISO3
# "coordinates" extracts centroids of the polygons, in the order listed at worldMap#data
centroids.df <- as.data.frame(coordinates(worldMap))
names(centroids.df) <- c("Longitude", "Latitude") #more sensible column names
# This shapefile contained population data, let's plot it.
popList <- worldMap#data$POP2005
pop.df <- data.frame(id = idList, population = popList, centroids.df)
ggplot(pop.df, aes(map_id = id)) + #"id" is col in your df, not in the map object
geom_map(aes(fill = population), colour= "grey", map = worldMap.fort) +
expand_limits(x = worldMap.fort$long, y = worldMap.fort$lat) +
scale_fill_gradient(high = "red", low = "white", guide = "colorbar", labels = comma) +
geom_text(aes(label = id, x = Longitude, y = Latitude)) + #add labels at centroids
coord_equal(xlim = c(-90,-30), ylim = c(-60, 20)) + #let's view South America
labs(x = "Longitude", y = "Latitude", title = "World Population") +
theme_bw()
Minor technical note: actually coordinates in the sp package doesn't quite find the centroid, but it should usually give a sensible location for a label. Use gCentroid in the rgeos package if you want to label at the true centroid in more complex situations like non-contiguous shapes.
The accepted answer here may work, but the actual question asked specifically notes that there is an error "ggplot2 doesn't know how to deal with data of class uneval."
The reason that it is giving you the error is because the inclusion of centroids.df needs to be a named variable (e.g. accompanied by "data=")
Currently:
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
Should be (note: "data=centroids.df"):
ggplot(data = region_of_interest.fort, aes(x = long, y = lat, fill = id, group = group)) +
geom_polygon() +
geom_text(data=centroids.df, aes(label = id, x = Longitude, y = Latitude)) +
scale_fill_gradient(high = "green", low = "red", guide = "colorbar") +
coord_equal() +
theme() +
ggtitle("Title")
This issue was addressed here: How to deal with "data of class uneval" error from ggplot2?