Построение путей большого круга

Я пытаюсь построить некоторые карты на основе пути/соединения, но не могу понять, как это сделать.

Я вижу много возможностей для метрик, основанных на одной точке (горячие точки преступности в Лондоне и т. д. с помощью googleVis, ggmap и т. д.), но я не могу найти слишком много примеров метрик, основанных на двух точках (иммиграция между городами, маршруты поездов и т. д.). .) Есть пример с пакетом geosphere , но, похоже, он недоступен для R 3.0.2.

В идеале я хотел бы что-то вроде этого пример D3, а также хотел бы настроить толщина, цвет и т. д. линий и кругов.

PS: я не думаю, что rCharts может сделать это прямо сейчас, верно?


person TheComeOnMan    schedule 27.10.2013    source источник
comment
geosphere доступен для R 3.0.2, если у вас возникли проблемы с установкой, я бы сначала сосредоточился на этой части. В R geosphere было бы моим первым портом захода по этому вопросу.   -  person mdsumner    schedule 28.10.2013
comment
Ты прав. Это как-то связано с пакетом sp. Я думал, что зависимости обновляются автоматически. Спасибо за внимание.   -  person TheComeOnMan    schedule 31.10.2013


Ответы (1)


Вот то, что я начал в прошлом году и так и не удосужился отполировать должным образом, но, надеюсь, это должно ответить на ваш вопрос о соединении точек на карте с большими круговыми линиями, с возможностью настройки линий, кругов и т. д.

Я использую (мой) пакет rworldmap для картографирования, WDI для данных всемирного банка и геосферу для линий большого круга. Цель состояла в том, чтобы отобразить потоки помощи от всех стран-доноров ко всем странам-получателям (по одному графику на каждого донора). Ниже приведен пример графика, а ниже код. Надеюсь, поможет. Было бы здорово найти время, чтобы забрать его снова! Энди

Карта потоков помощи с использованием пакетов rworldmap, WDI и геосферы

library(rworldmap)
library(WDI) # WORLD BANK INDICATORS

## lines of either type may obscure more than they add
##**choose line option here
addLines <- 'gc' #'none''straight' 'gc'
if ( addLines == 'gc' ) library(geosphere)

# setting background colours
oceanCol = rgb(7,0,30,maxColorValue=255) 
landCol = oceanCol 

#produces a list of indicator IDs and names as a matrix
indicatorList <- WDIsearch('aid flows')

#setting up a world map shaped plot window
#*beware this is windows specific
mapDevice('windows',width=10,height=4.5)


year <- 2000
#for(indNum in 1:2)
for(indNum in 1:nrow(indicatorList))
{
  indID <- indicatorList[indNum][1]
  donorISO3 <- substr(indID,start=8,stop=10)

  dFdonor <- WDI(indicator=indID,start=year,end=year)
  #divide by 10^6 for million dollars
  dFdonor[indID] <- dFdonor[indID] * 1/10^6

  sPDFdonor <- joinCountryData2Map(dFdonor,nameJoinColumn='country',joinCode='NAME')
  #take out Antarctica
  sPDFdonor <- sPDFdonor[-which(row.names(sPDFdonor)=='Antarctica'),]

  legendTitle=paste("aid flow from",donorISO3,year,"(millions US$)") 
  mapBubbles(sPDFdonor, nameZSize=indID, plotZeroVals=FALSE, legendHoriz=TRUE, legendPos="bottom", fill=FALSE, legendTitle=legendTitle, oceanCol=oceanCol, landCol=landCol,borderCol=rgb(50,50,50,maxColorValue=255),lwd=0.5,lwdSymbols=1)
  #removed because not working , main=paste('donor', donorISO3,year)

  #now can I plot lines from the centroid of the donor to the centroids of the recipients
  xDonor <- sPDFdonor$LON[ which(sPDFdonor$ISO3==donorISO3) ]
  yDonor <- sPDFdonor$LAT[ which(sPDFdonor$ISO3==donorISO3) ] 
  xRecips <- sPDFdonor$LON[ which(sPDFdonor[[indID]] > 0) ]
  yRecips <- sPDFdonor$LAT[ which(sPDFdonor[[indID]] > 0) ]
  amountRecips <- sPDFdonor[[indID]][ which(sPDFdonor[[indID]] > 0) ]


  ## straight lines
  if ( addLines == 'straight' )
  {
    for(line in 1:length(xRecips))
    {  
       #col <- 'blue'
       #i could modify the colour of the lines by the size of the donation
       #col=rgb(1,1,1,alpha=amountRecips[line]/max(amountRecips))
       #moving up lower values
       col=rgb(1,1,0,alpha=sqrt(amountRecips[line])/sqrt(max(amountRecips)))
       lines(x=c(xDonor,xRecips[line]),y=c(yDonor,yRecips[line]),col=col, lty="dotted", lwd=0.5)   #lty = "dashed", "dotted", "dotdash", "longdash", lwd some devices support <1
    }
  }

  ## great circle lines
  ## don't work well when donor not centred in the map
  ## also the loop fails at CEC & TOT because not ISO3 codes
  if ( addLines == 'gc' & donorISO3 != "CEC" & donorISO3 != "TOT" )
  {  
    for(line in 1:length(xRecips))
    {
      #gC <- gcIntermediate(c(xDonor,yDonor),c(xRecips[line],yRecips[line]), n=50, breakAtDateLine=TRUE)
      #30/10/13 lines command failed with Error in xy.coords(x, y) : 
      #'x' is a list, but does not have components 'x' and 'y'
      #adding sp=TRUE solved
      gC <- gcIntermediate(c(xDonor,yDonor),c(xRecips[line],yRecips[line]), n=50, breakAtDateLine=TRUE, sp=TRUE)

      #i could modify the colour of the lines by the size of the donation
      #col=rgb(1,1,1,alpha=amountRecips[line]/max(amountRecips))
      #moving up lower values
      col=rgb(1,1,0,alpha=sqrt(amountRecips[line])/sqrt(max(amountRecips)))

      lines(gC,col=col,lwd=0.5)
    }
  }  

  #adding coasts in blue looks nice but may distract
  data(coastsCoarse)
  plot(coastsCoarse,add=TRUE,col='blue')

  #repeating mapBubbles with add=T to go on top of the lines
  mapBubbles(sPDFdonor, nameZSize=indID, plotZeroVals=FALSE, fill=FALSE, addLegend=FALSE, add=TRUE, ,lwd=2)
  #removed because not working : , main=paste('donor', donorISO3,year)

  #looking at adding country labels
  text(xRecips,yRecips,sPDFdonor$NAME[ which(sPDFdonor[[indID]] > 0) ],col=rgb(1,1,1,alpha=0.3),cex=0.6,pos=4) #pos=4 right (1=b,2=l,3=ab)

  #add a title 
  nameDonor <- sPDFdonor$NAME[ which(sPDFdonor$ISO3==donorISO3) ]
  mtext(paste("Aid flow from",nameDonor,year), cex = 1.8, line=-0.8)

  #savePlot(paste("C:\\rProjects\\aidVisCompetition2012\\Rplots\\greatCircles\\wdiAidFlowLinesDonor",donorISO3,year,sep=''),type='png')
  #savePlot(paste("C:\\rProjects\\aidVisCompetition2012\\Rplots\\greatCircles\\wdiAidFlowLinesDonor",donorISO3,year,sep=''),type='pdf')

} #end of indNum loop
person Andy    schedule 30.10.2013
comment
Это выглядит красиво, хорошая вещь. Я не уверен, как проверить, но векторизовано ли основное изображение карты? geosphere, кажется, не поощряет увеличение/уменьшение масштаба. Кроме того, поскольку похоже, что пакет не поддерживается активно, я буду только голосовать и не принимать ответ. Я надеюсь, что 15 баллов побудят вас снова заняться этим :) - person TheComeOnMan; 31.10.2013
comment
Спасибо! Да, карта rworldmap является векторной (sp SpatialPolygonsDataFrame). Вы можете сказать это, сохранив график в формате pdf (раскомментируйте предпоследнюю строку кода и отредактируйте путь), затем увеличьте масштаб, и вы увидите линии, а не пиксели. - person Andy; 31.10.2013