I am receiving the following error message when I run leaflet in the knitr program: ## Error in file(con, "rb"): cannot open the connection. There is no error message, however, when I run this program in regular r. I can't figure out what the problem is. Here is the code I am trying to use (I got it from https://www.paulamoraga.com/tutorial-geostatistical-data/#):
library(leaflet)
index <- inla.stack.index(stack = stk.full, tag = "pred")$data
prev_mean <- result$summary.fitted.values[index, "mean"]
raster_prev_mean <- rasterize(x = coop, y = ra, field = prev_mean, fun = mean)
pal <- colorNumeric("viridis", c(0, 1), na.color = "transparent")
leaflet() %>% addProviderTiles(providers$CartoDB.Positron) %>%
addRasterImage(raster_prev_mean, colors = pal, opacity = 0.5) %>%
addLegend("bottomright", pal = pal, values = values(raster_prev_mean), title = "Prevalence") %>%
addScaleBar(position = c("bottomleft"))
Did you install/include the packages from the start of the demo? Also the comment recommended you install phantomJS as well. If you don’t have these packages you will need to install them.
library(geoR)
library(phantomJS)
data(gambia)
Related
Given the following example data
mydata <- data.frame(
lat = c(21.05939, 21.04305, 21.05977, 21.04336, 21.04434),
lng = c(92.22692 ,92.23357 ,92.22733 ,92.23361 ,92.23478),
X1 = c("sometimes", "always", "never", "often", "rarely")
)
And the following Leaflet plot:
pal1 <- c("#003366","#00ced1", "#ffd700","#ffa500","#ff1a1a")
color <- colorFactor(pal1, domain = mydata$X1)
leaflet(data = mydata) %>%
addTiles() %>%
addCircleMarkers(lng = mydata$lng,
lat = mydata$lat,
color = ~color(mydata$X1)) %>%
addLegend("topright",
pal=color,
values=mydata$X1,
opacity = 1)
How can I manipulate the order of labels in the legend so that they are:
always,
often,
sometimes,
rarely,
never
I have attempted to specify the levels argument in colorFactor() and have also attempted the same with the values argument in addLegend However, the legend still resorts to alphabetical order of the items.
NVM I think I figured it out.
I first specified a sort order by:
sort_val = factor(mydata$X1, levels = c('always',
'often',
'sometimes',
'rarely',
'never'))
I then passed sort_val to the values argument in addlegend()
addLegend("topright",
pal=color,
values=sort_val,
opacity = 1)
I think this is correct unless anyone can suggest an alternative?
library(plotly)
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df$hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
l <- list(color = toRGB("white"), width = 2)
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
p <- plot_geo(df, locationmode = 'USA-states') %>%
add_trace(
z = ~total.exports, text = ~hover, locations = ~code,
color = ~total.exports, colors = 'Purples'
) %>%
colorbar(title = "Millions USD") %>%
layout(
title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g
)
p
The above code is from plotly website and the plot produced should be as follows:
However, the plot I generated by using the code is as follows:
What happens? Do I need to install some other packages to reproduce the correct plot?
I got this too. If you open the javascript console you can see an error:
Failed to load resource: Unable to init SSL Context:
while it is trying to open this file:
"https://cdn.plot.ly/world_110m.json"
Here is a screen shot:
Cause:
I believe this is because the non-professional Version of R-Studio does not support https by design, so there is probably no work around except wrapping it as markdown and viewing it in a browser as I describe below.
Workaround:
If you package it in R-markdown (put your code between the following lines):
```{r}
(your code here)
```
and then save it as an .Rmd file) and knit it. Then it will still not work in the R-Studio preview-browser, and but it does if you use the "Open in Browser" function and open it in Chrome (for example).
Or buy the professional version :).
I am creating a flexdashboard and including a leaflet map in it.
Once I added the map to the markdown file when the dashboard renders nothing appears on it, and I get the following warning in the R Markdown console:
Warning in normalizePath(path.expand(path), winslash, mustWork) :
path[1]="figure-html/chart_categories-1.mb.png": The system cannot find the path specified
Warning in normalizePath(path.expand(path), winslash, mustWork) :
path[1]="figure-html/chart_categories-1.png": The system cannot find the path specified
Now, the error is strange as if I run it independently of the dashboard it renders without an issue, it also renders without an issue when I create a new dashboard and the leaflet map is the only chunk but with the rest of my code it causes issues.
Also, if I run the dashboard without evaluating the map chunk it runs perfectly.
Any ideas what could be causing this?
My leaflet code below:
countries <- readOGR("/filepath")
country_map = sqlQuery(pa,"SELECT *
FROM [PortAnalyzer].[dbo].[Country] c
join BarraCountryRegion b on right(b.Factor,3) = c.CountryCode
where b.Model = 'GEM3L' and LEN(b.Factor)=9 ",stringsAsFactors = FALSE)
countries#data = countries#data %>% left_join(country_map,c('ISO_A3' = 'CountryCode'))
country_attribution = data_melt %>% filter(Category == 'Country' & Style =='Total' & variable == 'Total' &
!`Sub-Category` %in% c('Total','CASH'))
countries#data = countries#data %>% left_join(country_attribution,c('Factor' = 'Sub-Category'))
map <- leaflet(countries)
# Create a continuous palette function
pal <- colorNumeric(
palette = "Blues",
domain = countries$value
)
binpal = colorNumeric('RdYlGn',countries$value)
test = countries#data
# Apply the function to provide RGB colors to addPolygons
map %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,color = binpal(countries$value)
) %>%
addLegend("bottomright", pal = binpal, values = countries$value,
title = "Total Return",
labFormat = labelFormat(suffix = "%"),
opacity = 1
)
I was able to make it work by entering the Leaflet in the Shiny function:
renderLeaflet({})
I am experimenting with R highcharter package to create a bar chart function. the code is as below. I request help in
1-How to change the format of the dataLabels to percentage ?
2-How to set X-axis label display angle. I want to set it to 45 degrees
hcbar_categorycount_vertical <- function(data=x,var=y){
df <- data.frame(prop.table(table(data[var])))
names(df) <- c(var,'Proportion')
df$Proportion <- round(df$Proportion*100,2)
df <- df%>% arrange(-Proportion)
df[,1] <- as.character(df[,1])
df[,1] <- factor(df[,1], levels = df[,1])
df$Cumulative <- round(cumsum(df$Proportion),2)
highchart(debug = TRUE) %>%
hc_xAxis(categories=df[[1]]) %>%
hc_yAxis(labels = list(format = "{value}%"), max = 100) %>%
hc_add_series(name=var,data=df$Proportion,type = "column",dataLabels = list(enabled = TRUE, format='{point.label}%'))
}
I am not sure what should be the syntax of "format" within dataLabel property list.The above code does not seem to work. I already referred to the highcharter vignette and this site : http://jkunst.com/highcharter/highcharts-api.html#hc_xaxis-and-hc_yaxis
But could not find an answer. Thanks for the help in advance.
#jeganathan-velu,
1) Try changing the '{point.label}%'by '{point.y}%'
2) See the highcharts example. You need to add to the hc_xAxis the argument labels = list(rotation = 90)
highcharter package is just the wrapper of highcharts so you can check all the examples and the well documented API from highcharts. Replicating highcharts demos
Found the answer after trial and error and some further research in http://api.highcharts.com/highcharts#xAxis.labels.rotation
Posting the updated code component for the benefit of others.
hc_xAxis(categories=df[[1]],labels = list(rotation=-45)) %>%
hc_yAxis(labels = list(format = "{value}%"), max = 100) %>%
hc_add_series(name=var,data=df$Proportion,type = "column",dataLabels = list(enabled = TRUE, format='{point.y}%'))
Quick question all.
I have some data in sql server which i have loaded into RStudio. I have made a barchart for the data and now i am using leaflet library with the use of latitude and longitude to plot a point on the map. I want to be able to use popup to show a barchart in it when the user clicks on the point.
BarChart code (maybe this is a problem because i am using googleVis library so not sure if i can use this in the popup. but again this is the most appropriate bar graph i can make and need- other suggestions could be helpful as i am not a professional in R libraries yet)
Switzerland <- sqlQuery(con, "sql query")
SwitzerlandChart <- gvisBarChart(Switzerland, options = list(height=200))
For the graph plot the code is:
m <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addCircles(lng=8.498868, lat=46.9221, popup=paste(plot(SwitzerlandChart)))
When i run this code it opens a webpage to view my barplot.
Then i run the following:
m #Prints the graph
This prints the graph with the point in the desired location but the popup shows me a webpage instead which also only i can open.
I want to be able to plot the bargraph inside the popup please.
Hope someone can help
Maybe a little late but here's a solution. The addPopups() function in library(leaflet) seems to be able to handle .svg files. Therefore, you could simply save your plot using svg() and then read it again using readLines(). Here's a reproducible example using library(mapview):
library(lattice)
library(mapview)
library(sp)
data(meuse)
coordinates(meuse) <- ~x+y
proj4string(meuse) <- CRS("+init=epsg:28992")
clr <- rep("grey", length(meuse))
fldr <- tempfile()
dir.create(fldr)
pop <- lapply(seq(length(meuse)), function(i) {
clr[i] <- "red"
p <- xyplot(meuse$cadmium ~ meuse$copper,
col = clr, pch = 20, alpha = 0.7)
svg(filename = paste(fldr, "test.svg", sep = "/"),
width = 250 * 0.01334, height = 250 * 0.01334)
print(p)
dev.off()
tst <- paste(readLines(paste(fldr, "test.svg", sep = "/")), collapse = "")
return(tst)
})
mapview(meuse, popup = pop, cex = "cadmium")
You will see that each popup is a scatterplot. As for a leaflet example, consider this:
content <- pop[[1]]
leaflet() %>% addTiles() %>%
addPopups(-122.327298, 47.597131, content,
options = popupOptions(closeButton = FALSE)
)
In case you need the plot to be interactive, you could have a look at library(gridSVG) which is able to produce interactive svg plots from e.g. lattice or ggplot2 plots.
UPDATE:
library(mapview) now has designated functionality for this:
popupGraph: to embed lattice, ggplot2 or interactive hatmlwidgets based plots.
popupImage: to embed local or remote (web) images
This is currently only available in the development version of mapview which can be installed with:
devtools::install_github("environmentalinformatics-marburg/mapview", ref = "develop"
This may be a little late too, but here is a full leaflet implementation. I first create the plot and then use the popupGraph function to add it in.
# make a plot of the two columns in the dataset
p <- xyplot(Home ~ Auto, data = Jun, col = "orange", pch = 20, cex = 2)
# make one for each data point
p <- mget(rep("p", length(Jun)))
# color code it so that the corresponding points are dark green
clr <- rep("orange", length(Jun))
p <- lapply(1:length(p), function(i) {
clr[i] <- "dark green"
update(p[[i]], col = clr)
})
# now make the leaflet map
m1 <- leaflet() %>%
addTiles() %>%
setView(lng = -72, lat = 41, zoom = 8) %>%
# add the markers for the Jun dataset
# use the popupGraph function
addCircleMarkers(data = Jun, lat = ~Lat, lng = ~Lon,
color = ~beatCol(BeatHomeLvl), popup = popupGraph(p),
radius = ~sqrt(BeatHome*50), group = 'Home - Jun') %>%
# layer control
addLayersControl(
overlayGroups = c('Home - Jun'
),
options = layersControlOptions(collapsed = F)
) %>%
# legend for compare to average
addLegend('bottomright', pal = beatCol, values = last$BeatTotalLvl,
title = 'Compare<br>Quote Count to<br>3Mos State Avg',
opacity = 1)
m1
Here is the output.