I have 20 UTM locations included below.
EDIT I have modified the included data to include the locations in Lat Long and added additional code below. I get the same result with either UTMs or Lat, Long. I have double checked the points in google earth and they are certainly within the extent of the BaseMap I define below. Any other suggestions...
Data <- structure(list(Latitude = c(43.383819, 43.383787, 43.383838,
43.384088, 43.392086, 43.393099, 43.388453, 43.384829, 43.399706,
43.40308, 43.408739, 43.40765, 43.407522, 43.413508, 43.418288,
43.416157, 43.417822, 43.417221, 43.417209, 43.417603), Longitude = c(-111.130989,
-111.130988, -111.130996, -111.129578, -111.122884, -111.12143,
-111.126514, -111.12809, -111.125333, -111.126616, -111.139745,
-111.140401, -111.140614, -111.161305, -111.158135, -111.153607,
-111.141158, -111.13867, -111.138528, -111.138884), UTM_E = c(489389.998429055,
489390.073847615, 489389.434748439, 489504.334690555, 490047.849470232,
490165.770080405, 489753.250369502, 489624.98731782, 489850.781221576,
489747.455360571, 488685.407063201, 488632.089708587, 488614.819667178,
486940.804672798, 487198.453753294, 487564.574155778, 488572.710048877,
488774.012335271, 488785.505688775, 488756.758707237), UTM_N = c(4803447.00888757,
4803443.45497495, 4803449.11983808, 4803476.70438902, 4804364.10875695,
4804476.43597084, 4803961.08216192, 4803558.81058659, 4805210.65084223,
4805585.51119635, 4806215.67635871, 4806094.82531047, 4806080.6391722,
4806748.45554565, 4807278.81358453, 4807041.46688704, 4807224.59410279,
4807157.51112311, 4807156.15933319, 4807199.96352795)), .Names = c("Latitude",
"Longitude", "UTM_E", "UTM_N"), row.names = c(NA, 20L), class = "data.frame")
And I can plot them in using ggplot
library(ggplot2)
ggplot(aes(x = UTM_E, y = UTM_N), data = Data )+ geom_point()
ggplot(aes(x = Latitude, y = Longitude), data = Data )+ geom_point()
However I want to plot them over a map base layer using qmap and have specified the object below.
library(ggmap)
Area <- "palisades wyoming"
BaseMap <- qmap(Area , zoom = 10)
BaseMap
Following the helpful ggmap site linked here, I am trying to plot the points over the base map with the following code
BaseMap + geom_point(aes(x = UTM_E, y = UTM_N), data = Data )
BaseMap + geom_point(aes(x = Latitude, y = Longitude), data = Data )
but get the following warning
Removed 20 rows containing missing values (geom_point).
Why are the values missing when not mapped with ggplot(), but only included with geom_point()
Mapping the points within ggplot() return the following error incompatability between ggplot() and qmap()
BaseMap + ggplot(aes(x = UTM_E, y = UTM_N), data = Data )+ geom_point()
Error in p + o : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("+.gg", "Ops.data.frame") for "+"
Thanks in advance.
You can combine them. Don't add your map to an object, just call it with the geom_point code:
qmap(Area , zoom = 10) + geom_point(aes(x = UTM_E, y = UTM_N), data = Data )
And you'll get your map printed.
Good Luck!
Related
I would like to reproduce plot of spatial dependency of regions in ggplot2 rather then using basic plot in R
I provided reproduceble example in code below:
I followed example: Plotting neighborhoods network to a ggplot maps
library(leaflet)
library(ggplot2)
library(sf)
library(spdep)
URL <- "https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_CZE_1_sp.rds"
data <- readRDS(url(URL))
ggplot() +
geom_polygon(data = data, aes(x=long, y = lat, group = group), color = "black", fill = F)
cns <- knearneigh(coordinates(data), k = 3, longlat=T)
scnsn <- knn2nb(cns, row.names = NULL, sym = T)
cns
scnsn
cS <- nb2listw(scnsn)
summary(cS)
# Plot of regions and k-nn neighthorhours matrix
plot(data)
plot(cS, coordinates(data), add = T)
I am asking how to reproduce Plot of regions and k-nn neighthorhours matrix using ggplot.
I know we have to retrive each point input and then use geom_segment, however I dont know how to retrive it from cS object.
The other SO post you are refering contains all steps you need to follow to get your plot (thanks to the great answer from #StupidWolf).
Basically, you need to extract the different segment using:
1) Transform coordinates of data in a dataframe, it will facilitate its use later:
data_df <- data.frame(coordinates(data))
colnames(data_df) <- c("long", "lat")
This data_df contains now all x,y values for plotting points.
2) Now, we can retrieve segments informations from the cS object using:
n = length(attributes(cS$neighbours)$region.id)
DA = data.frame(
from = rep(1:n,sapply(cS$neighbours,length)),
to = unlist(cS$neighbours),
weight = unlist(cS$weights)
)
DA = cbind(DA, data_df[DA$from,], data_df[DA$to,])
colnames(DA)[4:7] = c("long","lat","long_to","lat_to")
In the DA dataframe, you have all informations required to draw each segments
3) Finally, you can put plot every parts:
ggplot(data, aes(x = long, y =lat))+
geom_polygon(aes(group = group), color = "black", fill = FALSE)+
geom_point(data = data_df, aes(x= long, y = lat), size = 1)+
geom_segment(data = DA, aes(xend = long_to, yend = lat_to), size=0.5)
Again, the solution provided by #StupidWolf was pretty well written and understandable, so I don't know why you were not able to reproduce it.
I am using R as a GIS tool for creating maps.
I wanted to create a contour, or heatmap of a species distribution on a geographical area.
I wanted to see on the map where each species (animal or plant) is present and color the area in a specific color.
I am using a dataset downloaded from GBIF.
You can download the datasets from my GitHub ([https://github.com/RosarioIacono/stackoverflow_question/blob/master/species2t.csv][1]).
species <- read.delim("./species.txt")
library(readr)
species2t <- read_csv("species2t.csv")
View(species2t)
ggmap(map1)+
stat_density_2d(data = subset(species2t, order=="Anseriformes"),
aes( x = decimalLongitude,
y = decimalLatitude,
fill = ..level..),
alpha = .3,
geom = "polygon",
color = species)+
theme(legend.position = "none")
But I get an error:
Error: Aesthetics must be either length 1 or the same as the data (190): colour
I don't have your data frame, but I think your problem comes with one of the groups having n=1. This can be caused by, some of your species_dens's longitude and latitude being out of the map:
library("ggmap")
map <- c(left = -0.7, bottom = 53, right =-0.3 , top =53.6 )
map1<-get_stamenmap(map, maptype = "toner-lite")
#simulate data
species_dens = data.frame(species=c("A","B","A","B"),
decimalLongitude=c(-0.4,-0.5,-0.3,-0.2),
decimalLatitude=c(53.1,53.2,53.3,53.4))
# returns your error
ggmap(map1)+
geom_density_2d(data = species_dens,aes( x = decimalLongitude,
y = decimalLatitude,
colour = species))
From the above, you can see the last data point is off the map, so if you do geom_density with your limits, the species "B" will have n=1. Using your current dataset, if you set the colors to be species, you still end up with n=1:
library(readr)
species2t <- read_csv("species2t.csv")
X=subset(species2t, order=="Anseriformes")
table(X$species)
Anas crecca Anas platyrhynchos Anas strepera Anser anser
1 1 1 1
Aythya fuligula Cygnus olor Tadorna tadorna
1 1 1
This means you cannot colour according to species. But you see how this order is distributed:
ggmap(map1)+
stat_density_2d(data = X,
aes( x = decimalLongitude,
y = decimalLatitude,
fill = ..level..),
alpha = .3,
geom = "polygon")+
theme(legend.position = "none")
I keep getting this error when trying to make a map...
Error in geom_map(data = all_states, map = all_states, mapping = aes(map_id = State, :
all(c("x", "y", "id") %in% names(map)) is not TRUE
My code so far...
all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true",
header = TRUE,
sep = ";")
all_states$State = state.name[match(all_states$State, state.abb)]
all_states = na.omit(all_states)
ggplot(data = all_states, aes(map_id = State)) +
geom_map(data = all_states,
map = all_states,
mapping = aes(map_id=State,x=Longitude,y=Latitude)) +
coord_fixed()
What am I doing wrong?
2 Problems.
You did not download the correct map. geom_map needs data for creating polygons, but your data contains the coordinates for cities
geom_map is very peculiar and restrictive about column names in data frames
Solution
get the right map (e.g., Just use the maps package for US)
rename the columns
I have also removed one or two lines and 'fortified' the data frame, as this is usually recommended before using it for maps.
library(tidyverse)
all_states = read.csv(file = "https://public.opendatasoft.com/explore/dataset/us-zip-code-latitude-and-longitude/download/?format=csv&timezone=America/New_York&use_labels_for_header=true", header = TRUE, sep = ";")
all_states = na.omit(all_states) %>%
mutate(region = State, long=Longitude, lat = Latitude) %>%fortify
US <- map_data('usa')
#>
#> Attaching package: 'maps'
#> map
ggplot()+
geom_map(data = US, map = US, mapping = aes( map_id = region, x = long, y = lat), fill = 'white') +
# now this is the US background
geom_point(data = filter(all_states, ! region %in% c('HI','AK','AS')), aes(x = long, y = lat), size = .01, color = 'black')
# and this is YOUR data. Use geom_point for it!!!
#I have removed Alaska, Hawaii and a third little bit which I ignorantly don't know. 'AS'.
#> Warning: Ignoring unknown aesthetics: x, y
Created on 2019-08-02 by the reprex package (v0.2.1)
I am reading a csv file and I want to plot places using the longitude and latitude mentioned in the file. The temperature at those places is also mentioned in the csv and I want to draw a heatmap using that temperature value.
I have read the csv file in variable st and created a dataframe extracting latitude,longitude and temperature.
I was plotting the map and created the heatmap. I have passed the temperature as the data in stat_density2d. I get the error "ggplot2 doesn't know how to deal with data of class integer"
Following is the code:
library(ggmap)
st <- read.csv("C:/Python27/csv/daily.csv")
longitude <- st$longitude
latitude <- st$latitude
temperature <- st$temperature
df <- data.frame(longitude,latitude,temperature)
houston <- get_map(location = c(lon = st$longitude[1], lat = st$latitude[1]), zoom = 6)
ggmap(houston)
ggmap(houston) +
# make the heatmap
stat_density2d(aes(x = longitude,
y = latitude,
fill = ..level.., # value corresponding to discretized density estimates
alpha = ..level..),
bins = 2, # number of bands
data <- df[,3] ,
geom = "polygon") + coord_fixed(xlim = c(-119,-121),ylim = c(35,37),ratio=1/1)+
scale_fill_gradient(low = "yellow", high = "red") +
scale_alpha(range = c(.25, .55)) +
theme(legend.position="none")
The sample csv file is shown below:
Name,latitude,longitude,temperature,
Five Points,36.34,-120.11,
Shafter/USDA,35.53,-119.28,
Firebaugh/Telles,36.85,-120.59,
Stratford,36.16,-119.85,67,
Kettleman,35.87,-119.89,50,
Parlier,36.60,-119.50,73,
Blackwells Corner,35.65,-119.96,70,
Los Banos,37.01,-120.76,75,
Fresno State,36.82,-119.74,0,
Westlands,36.63,-120.38,69,
first of all, I apologise.
I know there is numerous threads about this error, however I have tried numerous solutions and I have not managed to get any to solve my issue.
I have tried transforming my data into numerous forms but I still get the same error, or that ggplot2 does not support that data format.
Here is my code:
library(ggmap)
library(ggplot2)
library(data.table)
setwd("~/Projects/reformat")
map <- get_map(location = c(-4,54.5), zoom = 6)
data <- read.csv('lonlatprice.csv')
colnames(data) <- c('Longitude','Latitude','Price')
ggmap(map, extent = "device") + geom_point(aes(x = data$Longitude, y = data$Latitude), colour = "red",
alpha = 0.1, size = 2)
This is what the data format is like:
> head(data)
Longitude Latitude Price
1 53.778274 -2.48129 147500
2 52.833819 -0.936527 182000
3 50.792457 0.046043 193000
4 51.476984 -0.612126 580000
5 51.460139 -0.01867 905000
6 52.235942 1.519404 641500
Thanks in advance for help, I have only asked as a last resort after numerous days of no success.
There are several problems with your code:
You retrieved the wrong map. You mixed up the order of the lon and lat values in get_map(location = c(-4,54.5), zoom = 6)
You are calling the data in the geom_point part in the wrong way.
The following code fixes these problems:
map <- get_map(location = c(51.5,0.2), zoom = 6)
ggmap(map) +
geom_point(data= data,
aes(x = Longitude, y = Latitude),
colour = "red",
alpha = 0.5,
size = 4)
and gives you this map: