Domanda

Nota:Questa domanda è specifica per la mappatura, ma mi piacerebbe essere in grado di usarla quando traccio in un sistema di coordinate cartesiane standard.

Amo la grafica di base, ma mi piace anche ggplot2 per molte cose.Una delle mie funzioni di base più utilizzate per la messa a punto di un grafico è locator (n), ma questo produce un errore in ggplot2.

library(ggplot2) 
county_df <- map_data('county')  #mappings of counties by state
ny <- subset(county_df, region=="new york")   #subset just for NYS
ny$county <- ny$subregion

ggplot(ny, aes(long, lat, group=group)) +  geom_polygon(colour='black', fill=NA)
locator(1)

Ora grid.locator() come mi ha fatto notare Dason su talkstats.com (QUI) può restituire qualcosa.Non so come usare quel qualcosa per ottenere una coordinata della mappa.

> grid.locator()
$x
[1] 286native

$y
[1] 133native

Le unità non sembrano aiutare in quanto non sono coordinate della mappa.Forse ho bisogno di una sorta di conversione.

Grazie in anticipo.

MODIFICARE:(sulla base della risposta di DWin)

Dwin ha l'idea giusta, ma il fattore di conversione è un po ' fuori.Aiuto con questo sarebbe apprezzato.Nell'esempio qui sotto ho una mappa con un punto rosso su di esso alle coordinate (x = -73 & y = 40.855).Ho gettato la risposta di Dwin in una funzione per restituire le coordinate.Mi aspetto che i risultati siano le coordinate che ho inserito, ma non lo sono.

Idee?

require(maps); library(ggplot2); require(grid)

county_df <- map_data('county')  #mappings of counties by state
ny <- subset(county_df, region=="new york")   #subset just for NYS
ny$county <- ny$subregion


NY <- ggplot(ny, aes(long, lat)) +  
          geom_polygon(aes(group=group), colour='black', fill=NA) +
          coord_map() + geom_point(aes(-73, 40.855, colour="red"))
NY  

gglocator <- function(object){
    require(maps); require(grid)
    z <- grid.locator("npc")
    y <- sapply(z, function(x) as.numeric(substring(x, 1, nchar(x))))
    locatedX <- min(object$data$long) + y[1]*diff(range(object$data$long))
    locatedy <- min(object$data$lat)  + y[2]*diff(range(object$data$lat))
    return(c(locatedX, locatedy))
}

#click on the red dot
gglocator(NY)  #I expect the results to be x = -73 & y = 40.855

MODIFICA 2:(Uscendo dalla risposta di Baptise)

Ci siamo

NY <- ggplot(ny, aes(long, lat)) +  
          geom_polygon(aes(group=group), colour='black', fill=NA) +
          coord_map() + geom_point(aes(-73, 40.855, colour="red")) +
          scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0))


NY 
x <- grid.ls()[[1]][grep("panel-", grid.ls()[[1]])] #locate the panel
seekViewport(x)
y <-  grid.locator("npc")
y <- as.numeric(substring(y, 1, nchar(y)-3))

locatedX <- min(NY$data$long) + y[1]*diff(range(NY$data$long))
locatedy <- min(NY$data$lat) + y[2]*diff(range(NY$data$lat))
locatedX; locatedy 

AGGIORNARE: Il gglocator funzione del pacchetto ggmap ora contiene questa funzionalità.

È stato utile?

Soluzione

Ottengo il risultato corretto se aggiungo scale_x_continuous(expand=c(0,0)) + scale_y_continuous(expand=c(0,0)) alla trama, e seekViewport("panel-3-4") prima grid.locator()

Altri suggerimenti

È necessario utilizzare un sistema unitario che ha senso e salvare le informazioni nell'oggetto GGPLOT in modo da poter convertire da unità "NPC" nelle unità Mappa:

require(maps)
require(grid)
NY <- ggplot(ny, aes(long, lat, group=group)) +  geom_polygon(colour='black', fill=NA)
 grid.locator("npc")
# clicked in middle of NY State:

#$x
#[1] 0.493649231346082npc
#
#$y
#[1] 0.556430446194226npc
 range(NY$data$long)
#[1] -79.76718 -71.87756
 range(NY$data$lat)
#[1] 40.48520 45.01157
 locatedX <- min(NY$data$long) + 0.493649231346082*diff(range(NY$data$long))
 locatedX
#[1] -75.87247
locatedY <- min(NY$data$lat) +  0.556430446194226*diff(range(NY$data$lat))
locatedY
#[1] 43.00381
.

Ecco i risultati finali usando tutto ciò che DWIN e Battezza mi ha dato avvolto in una funzione.Ho anche chiesto la lista di GGPlot Guida e riporterò e riporterà ulteriori informazioni qui.

require(maps); require(ggplot2); require(grid)

ny <- map_data('county', 'new york')

NY1 <- ggplot(ny, aes(long, lat)) +  
          geom_polygon(aes(group=group), colour='black', fill=NA) +
          coord_map() + geom_point(aes(c(-78, -73), c(41, 40.855), 
          colour=c("blue", "red"))) + opts(legend.position = "none") 

NY <- NY1 + scale_x_continuous(expand=c(0,0)) + 
          scale_y_continuous(expand=c(0,0))
          #the scale x and y have to be added to the plot

NY 

ggmap.loc <- function(object){
    x <- grid.ls()[[1]][grep("panel-", grid.ls()[[1]])] #locate the panel
    seekViewport(x)
    y <-  as.numeric(grid.locator("npc"))
    locatedX <- min(object$data$long) + y[1]*diff(range(object$data$long))
    locatedy <- min(object$data$lat) + y[2]*diff(range(object$data$lat))
    return(c(locatedX, locatedy))
}

ggmap.loc(NY)
.

Ho scritto alla lista di GGLOT HELP e ha ricevuto una risposta molto utile da David Kahle che è accaduto ad essere interessato allo stesso problema.La sua funzione è fantastica in questo:

1) Non è necessario aggiungere la scala Y e scala x alla trama

2) Può trovare più punti contemporaneamente e restituirli come frame dati

3) Funziona su qualsiasi tipo di GGPlot, non solo mappe

gglocator <- function(n = 1, object = last_plot(), 
    message = FALSE, xexpand = c(.05,0), yexpand = c(.05, 0)){ 

  #compliments of David Kahle
  if(n > 1){
    df <- NULL
    for(k in 1:n){
      df <- rbind(df, gglocator(object = object, message = message, 
        xexpand = xexpand, yexpand = yexpand))
    }
    return(df)
  }

  x <- grid.ls(print = message)[[1]]
  x <- x[ grep("panel-", grid.ls(print=message)[[1]]) ] #locate the panel
  seekViewport(x)
  loc <-  as.numeric(grid.locator("npc"))

  xrng <- with(object, range(data[,deparse(mapping$x)]))
  yrng <- with(object, range(data[,deparse(mapping$y)]))    

  xrng <- expand_range(range = xrng, mul = xexpand[1], add = xexpand[2])
  yrng <- expand_range(range = yrng, mul = yexpand[1], add = yexpand[2])    

  point <- data.frame(xrng[1] + loc[1]*diff(xrng), yrng[1] + loc[2]*diff(yrng))
  names(point) <- with(object, c(deparse(mapping$x), deparse(mapping$y)))
  point
}

#Example 1
require(maps); library(ggplot2); require(grid)
county_df <- map_data('county')  #mappings of counties by state
ny <- subset(county_df, region=="new york")   #subset just for NYS
ny$county <- ny$subregion


NY <- ggplot(ny, aes(long, lat)) +  
          geom_polygon(aes(group=group), colour='black', fill=NA) +
          coord_map() + geom_point(aes(c(-78, -73), c(41, 40.855), 
          colour=c("blue", "red"))) + opts(legend.position = "none") 


NY 
gglocator(2)

#Example 2
df <- data.frame(xvar = 2:10, yvar = 2:10)
ggplot(df, aes(xvar, yvar)) + geom_point() + geom_point(aes(x = 3, y = 6))
gglocator()
.

Aggiornamento: La funzione gglocator di Pacchetto GGMap ora contiene questa funzionalità.

Questi post sono stati molto utili, ma sono passati alcuni anni, quindi alcune cose sono rotte.Ecco alcuni nuovi codici che funziona per me.Il codice per trovare la viewport corretto non ha funzionato, quindi invece ho usato current.vpTree() per cercare manualmente la vista destra, quindi copiati in seekViewport().Nota La vista per me era 'panel.6-4-6-4' e non il vecchio stile panel-*.Infine, non stavo ottenendo le risposte giuste durante il rendering a Rstudio, invece dovevo usare x11().

Ecco un esempio completo.Spero che questo sia utile.

library(ggplot2)
library(grid)

object<-ggplot(dat=data.frame(x=1:5,y=1:5),aes(x=x,y=y)) + 
  geom_point()  +
  scale_x_continuous(expand=c(0,0)) +
  scale_y_continuous(expand=c(0,0))
x11()
print(object)
formatVPTree(current.vpTree()) #https://www.stat.auckland.ac.nz/~paul/useR2015-grid/formatVPTree.R
seekViewport('panel.6-4-6-4')
y <-  as.numeric(grid.locator("npc"))
locatedX <- min(object$data$x) + y[1]*diff(range(object$data$x))
locatedY <- min(object$data$y) + y[2]*diff(range(object$data$y))
locatedX; locatedY
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top