Interactive zoom maps on R - maps

So I am doing a project where I am looking to create a US map with counties. I currently have a map successfully created but am looking to refine it. I am interested in generating a map in which it will show the US with states and if I clicked on a state it would zoom in and show the state with counties listed. Then I want to be able to click on the county to get corresponding information that is in a data set in R. Is this possible to do in R and if so any help would be greatly appreciated.
This is the code I am currently using:
library(devtools)
find_rtools()
devtools::install_github("hafen/housingData")
library(housingData);library(devtools)
head(geoCounty)
geo <- divide(geoCounty, by = c("state", "county"))
geo[[1]]
install.packages(maps)
install.packages(maptools)
library(maps)
library(maptools)
US <- map("state",fill=TRUE, plot=FALSE)
US.names <- US$names
US.IDs <- sapply(strsplit(US.names,":"),function(x) x[1])
US_poly_sp <- map2SpatialPolygons(US,IDs=US.IDs,proj4string=CRS("+proj=longlat
+ datum=wgs84"))
plot(US_poly_sp,col="white",axes=TRUE)
points(geoCounty$lon, geoCounty$lat)
Thanks,
Joey

Joey,
how about this?
library(mapview)
library(raster)
counties <- getData("GADM", country = "USA", level = 2)
mapview(counties)
Best
Tim

Related

Swin Transformer attention maps visualization

I am using a Swin Transformer for a hierarchical problem of multi calss multi label classification. I would like to visualize the self attention maps on my input image trying to extract them from the model, unfortunately I am not succeeding in this task. Could you give me a hint on how to do it?
I share you the part of the code in which I am trying to do this task.
attention_maps = []
for module in model.modules():
#print(module)
if hasattr(module,'attention_patches'): #controlla se la variabile ha l' attributo
print(module.attention_patches.shape)
if module.attention_patches.numel() == 224*224:
attention_maps.append(module.attention_patches)
for attention_map in attention_maps:
attention_map = attention_map.reshape(224, 224, 1)
plt.imshow(sample['image'].permute(1, 2, 0), interpolation='nearest')
plt.imshow(attention_map, alpha=0.7, cmap=plt.cm.Greys)
plt.show()
``
In addition if you know about some explainability techniques, like Grad-CAM, which could be used with a hierarchical Swin Transformer, feel free to attach a link, it would be very helpful for me.
I am also researching the same, while I don't have anything specific to SWIN. Here are some resources related to Vision Transformers. I hope it helps:
https://jacobgil.github.io/deeplearning/vision-transformer-explainability
https://github.com/jacobgil/vit-explain
https://github.com/hila-chefer/Transformer-Explainability
https://github.com/hila-chefer/Transformer-Explainability/blob/main/Transformer_explainability.ipynb

Error: no applicable method for 'bbox' applied to an object of Class "Extent"

I am plotting how collared animals utilise water points using the recurse package, and working through the code supplied here, with my data replacing Leo's data: http://dx.doi.org/10.5441/001/1.46ft1k05
I'm currently trying to map movement based on most frequently visited locations. However I keep getting an error in UseMethod "bbox".
When I use show(leoGeo), it returns as a Move object, and I have enabled and registered a Google API key. I have recurse, move, ggplot2, ggmap, RgoogleMaps, raster, scales, viridis, lubridate, reshape2, raster, rworldmap, aptools, cluster, amt, sp, rgdal,curl and dplyr loaded.
leovisit50 = getRecursions(leo.df, 50)
revisitThreshold = 75
leoGeo.map.df = as(leoGeo,'data.frame')
leoGeo.map.df$revisits = leovisit50$revisits
and when I go to use this command
map.leoGeo = qmap(bbox(extent(leoGeo[leovisit50$revisits >
revisitThreshold,])), zoom = 13, maptype = "road.Dist")
it keeps returning the error below
Error in UseMethod("bbox", x) :
no applicable method for 'bbox' applied to an object of class "Extent"
(I can provide full code for this if that is required, it was just the map.leoGeo line I was having difficulty with).
I'm new to movement analysis and am not sure how to fix this problem,any help would be greatly appreciated!
The method clearly exists
library(raster)
r <- raster()
e <- extent(r)
#bbox(e)
# min max
#s1 -180 180
#s2 -90 90
So probably you are loading a package that hides that method. As you are not calling the method directly, you cannot do raster::bbox. Start with a fresh R session, and see if there are warnings that tell you about this when you load your packages. Try to avoid loading many packages, and avoid those that hide methods in other packages.

Missing States in creating county map visuals using Python3 Vincent Vega

I am using Vincent to plot county level map for US. Took example data for 2016 elctions. It however doesnt plot for some states like California. I have checked data and FIPS codes seems to exist but still showing blank there. Any ideas what may be going on? I got county data from topo.json.
geo_data_c2 = [{'name': 'counties',
'url': county_topo,
'feature': 'us_counties.geo'}]
vis_election_counties = vincent.Map(data=merged, geo_data=geo_data_c2, scale=1000,
projection='albersUsa', data_bind='per_dem',
data_key='combined_fips', map_key={'counties': 'properties.FIPS'})
#Change our domain for an even inteager
vis_election_counties.scales['color'].domain = [0,1]
vis_election_counties.legend[![enter image description here][1]][1](title='per_dem')
vis_election_counties.to_json('vega.json')
vis_election_counties.display()
The FIPS codes for counties in the first ~7 states alphabetically need to be zero-padded to 5 characters.
Arapahoe County, CO has FIPS code 8005, which is represented as "08005" in https://raw.githubusercontent.com/jgoodall/us-maps/master/topojson/county.topo.json
merged['combined_fips'] = merged['combined_fips'].map(lambda i: str(i).zfill(5))

ARIMA MODEL Forecast PLOT in R

I'm currently doing arima forecasting in R and i'm already on the last step of displaying the forecast result but I am having trouble in displaying the forecast on the graph.
Here is my code:
mydata.arima005 <- arima(d.y, order= c(0,0,5))
mydata.pred1 <- predict (mydata.arima005, n.head =100)
plot(d.y)
lines(mydata.pred1$pred, col="blue")
lines(mydata.pred1$pred+2*mydata.pred1$se, col="red")
lines(mydata.pred1$pred-2*mydata.pred1$se, col="red")
So as you can see, I want my graph to show the forecast values in color blue and the confidence interval on red. But this is what I am getting instead.
So as you can see it's not color coded at all. My code contains no error.
This is a sample of the output I am expecting(got it from youtube)I used the same codes used in this video I got thats why i was wondering why my graph doe not look like this.Hope you could help
The forecast package has some functions for displaying nice plots of the forecasts and prediction intervals.
You would need something like this:
library(forecast)
mydata.arima005 <- Arima(d.y, order= c(0,0,5))
mydata.pred1 <- forecast(mydata.arima005, h=100)
plot(mydata.pred1)
Or using ggplot2 graphics:
library(ggplot2)
autoplot(mydata.pred1)

Plotly in R Power BI

How I can create interactive R plots in Power BI (for example Plotly)? Below code doesn't return any error, but also doesn't show chart:
library(plotly)
library(ggplot2)
z = ggplot(data = dataset) + geom_point(mapping = aes(x = Console, y = Search))
ggplotly(z)
Data source:
source <- "https://cdn.rawgit.com/BlueGranite/Microsoft-R-Resources/master/power-bi/gameconsole.csv"
game.console <- read.csv(source, header = TRUE)
According to this question in Power BI's Community forums
Plotly lib is supported as part of HTML support for R powered Custom
Visuals only, not R Visuals in general currently.
Plotly can only be used if it produces an IMAGE\PNG for R visuals in
PBI. Not HTML.
For Custom Visuals we have an upcoming feature which will also enable R-based custom visuals to render as htmls.
Hope this helps.
The reason is that right now Power BI only supports render charts created by R visualization component as PNG.
Try the following:
p <- plot_ly(x = dataset$period, y = dataset$mean, name = "spline", line = list(shape = "spline"))
plotly_IMAGE(p, format = "png", out_file = "out.png")
But the problem with this is that, though rendered by plotly, the visualizations will not be interactive since its just a PNG image.
If you want to create interactive visualizations using plotly. The only way you can do is to create a custom Power BI visualization and import it to your report. See this post for a good introduction.
PowerBI only supports charts rendered as PNG while plotly format is in HTML. You can try to save the chart as PNG then print it in the R console inside PowerBI.
You first have to register a plotly account here.
After registration, on the top right corner arrow next to your account name and click on Settings -> API keys. You will be able to generate API key. Copy and paste your username and API key using this code.
Sys.setenv("plotly_username"="....")
Sys.setenv("plotly_api_key"=".....")
Then add this code in to turn the plot into png format and print it out.
fig <- plot_ly(x = dataset$Console, y = dataset$Search)
Png <- plotly_IMAGE(fig, out_file = "plotly-test-image.png")
print(Png)
As mentioned in another answer, this plot won't be interactive as plot in PowerBI. To create an interactive plot in PowerBI, you have to create a custom visual. Follow an R custom visual example here or radacad example here.

Resources