Manually adding legend values in leaflet - r

I'm plotting results from various British elections in Leaflet and ran into a bit of a problem with legends.
For the various results in the general election I'm using the same colour function with different domain for the different data (the yellow-> purple scale in the picture)
This is created with (for the first two as examples):
labvotescols <- colorNumeric(
c("Yellow", "Purple"),
domain = Westminster$LabourVotes,
ukipvotescols <- colorNumeric(
c("Yellow", "Purple"),
domain = Westminster$UKIPVotes,
and so on...
Currently I have the legend
map = map %>% addLegend("bottomright", pal = ukipvotescols, values = Westminster$UKIPVotes,
title = "(e.g.) % voting UKIP at GE2015",
opacity = 1)
as one example of this, but really I'd like to get rid of all the values on the legend and just have "less" at the yellow end and "more" at the purple end. Is this possible?
I tried playing around and then googling but to no avail.

You could change it from a yellow -> purple scale and make your own scale:
map %>%
addLegend("bottomright",
colors = c("#FFC125", "#FFC125", "#8A4117", "#7D0552", "#571B7E"),
labels = c("less", "", "", "", "more"),
title = "(e.g.) % voting UKIP at GE2015",
opacity = 1)
If you get the correct colors then it should look similar. Not the answer you were looking for, but it's a good workaround. Your output would look like this:
Spend more time looking for better color transition and you could get a legend that looks similar to the yellow-purple color pallet you have up top.

Related

Changing color for two groups in leaflet for flow map (R)

I have replicated the flow map from a template (here).
I was wondering how I could change the color by grouping. Right now, I have modified the template so that all flows going to the same destination have the same color. However, I was wondering if instead, it would be possible to change the colors for the origins as well, but grouped together. So for example, all flows to Colorado would be different shades of blue, all flows to Texas would be different shades of orange, etc.
The below code is exact same as the linked source, except I have switched "origins" to "destinations"
pal <- colorFactor(brewer.pal(4, 'Set2'), flows$destinations)
leaflet() %>%
addProviderTiles('CartoDB.Positron') %>%
addPolylines(data = flows, weight = ~rootcounts, label = hover,
group = ~destinations, color = ~pal(destinations)) %>%
addLayersControl(overlayGroups = unique(flows$destinations),
options = layersControlOptions(collapsed = FALSE))
Thank you in advance!

How can I change a color of a surface in VineCopula::plot.BiCop function?

Do you know how I can change a color of a surface in VineCopula::plot.BiCop function? I've tried to use a col argument but it's worked just for color of lines of a grid.
library(VineCopula)
par.gauss<-BiCopTau2Par(1, .7, check.taus = TRUE)
obj.gauss <- BiCop(family = 1, par = par.gauss)
plot(obj.gauss,zlim=c(0,12))
I've tried:
plot(obj.gauss,zlim=c(0,12), col="green")
but it's changed just a color of lines.
You could use
n <- 70
plot(obj.gauss, zlim=c(0,12), col.regions=rainbow(n))
n gives the number of colors used in your plot. rainbow is a color palette, there are several others. Look at ?rainbow, you could use
hcl.colors(n)
rainbow(n)
heat.colors(n)
terrain.colors(n)
topo.colors(n)
cm.colors(n)
and there are several parameters, so for example
plot(obj.gauss, zlim=c(0,12), col.regions=rainbow(120, s=0.5, alpha=0.75))

R spplot: colorbar rather than legend for SpatialPoint data

I am plotting a SpatialPoint dataframe in R using spplot, and I would like to use a colorbar rather than a legend, to portray color values. (It's more efficient, and I want the map to "match" previous, raster data maps.) I'm sure this is possible, but can find no examples of it online. Could anyone give me a hint?
My current code is:
my.palette <- brewer.pal(n = 9, name = "Spectral")
my.palette<- rev(my.palette)
pols1 <- list("sp.lines", as(ugborder, 'SpatialLines'), col = gray(0.4), lwd = 1)
pols2 <- list("sp.polygons", as(water_ug, 'SpatialPolygons'), fill = 'skyblue1',col="transparent", first = FALSE)
spplot(ughouseszn,zcol="lzn_sg_clng",cex = .75,
key.space="right", digits=1,
par.settings = list(axis.line = list(col = 'transparent')),
xlim = bbox(ugborder)[1, ],ylim = bbox(ugborder)[2, ],
col.regions = my.palette, cuts=8,
sp.layout=list(pols1, pols2))
Where ugborder and water_ug give Uganda's borders and water, ughouseszn is a SpatialPointsDataframe, and the resulting map is here:
(As a side note, I'm hoping that adding a colorbar will lead to a more efficient use of space -- right now there's a lot of extra space at the top and bottom of Uganda's border, which is useless, and also does NOT appear when I map raster data using spplot, with the same pols1 and pols2.)
If "lzn_sg_clng" is converted to a factor, does this give you the map you desire? (rendering by the category rather than a graduated scale).

Add "rgb" legend to R leaflet heatmap

I made some interactive heatmaps using leaflet (particularly the addHeatmap() command from the leaflet.extras package) and shiny. Having created a desired map, I would like to add a legend to it.
What I am interested in is a "rgb" legend, based on density values deduced by addHeatmap() from pure long/lat coords.
What I need is something like this map - https://www.patrick-wied.at/static/heatmapjs/example-legend-tooltip.html - unfortunately I have no knowledge of JS and can't rewrite this code in terms of R/include the right fragment of JS code for my problem.
What I tried so far is the addLegend() command, which does not give the desired result, as in this case I would need to specify a variable for which the legend would be prepared. I also tried to extract the color range and assigned values from created leaflet object, however with no success.
Here's link to full data to run the reproducible example on:
https://drive.google.com/file/d/1h3jL_PU6DGTtdIWBK02Tt37R7IB2ArH9/view
And here's top 20 records:
structure(list(latitude = c(30.309522, 30.24429616, 30.30038194,
30.27752338, 30.23294081, 30.23038507,
30.34285933, 30.24962237, 30.26594744,
30.20515821, 30.22363485, 30.2759184,
30.28283226, 30.33816909, 30.26611565,
30.18835401, 30.26704789, 30.27456699,
30.19237135, 30.1925213),
longitude = c(-97.73171047, -97.77446858, -97.77885789,
-97.71919076, -97.58937812, -97.76581095,
-97.73598704, -97.72215443, -97.74144275,
-97.8782895, -97.78329845, -97.71321066,
-97.70820152, -97.82413058, -97.7327258,
-97.81606795, -97.68989589, -97.7580592,
-97.7816127, -97.73138523)),
.Names = c("latitude", "longitude"), row.names =
c(NA, 20L), class = "data.frame")
Here's an example code, which I'd like to extend by the mentioned functionality:
library(magrittr)
library(leaflet)
library(leaflet.extras)
data <- read.csv('DATA.csv')
leaflet(data) %>%
addTiles(group="OSM") %>%
addHeatmap(group="heat", lng = ~longitude, lat = ~latitude, max=.5, blur = 60)
And here is the result of that code (on whole dataset):
https://i.stack.imgur.com/6VFNC.jpg
So to sum up what I would like to do: based on such picture I would like to extract the range of the drawn colors along with values assigned to them, and draw legend using that information.
Is there something I am missing? It looks like a pretty simple issue, but I've been struggling to find a solution for past few hours.
Thanks in advance for any help!
EDIT: extended the reproducible example.
Your sample data does not have any values to it to actually map a density overlay.
You can specify the number of bins with colorBin() and then specify those bins with your pal function. You can set the bins differently depending on your needs at the data_values distributions. The help section of colorBin() is helpful in identifying the correct parameters for your needs.
bins <- c(0,1,2,3,4)
pal <- colorBin("Spectral", domain = data_value, bins = bins, na.color = "transparent")
m <-leaflet() %>%
addTiles() %>%
addHeatmap(lng= long_cords, lat = lat_cords, intensity = data_value,
blur = 20, max = 400, radius = 15, cellSize = 3) %>%
addLegend(pal = pal, values = data_value,
title="Heat map legend")
You'll have to play around with the addHeatmap arguments to get an the right transparency and density settings.

r bokeh chart legend - placed poorly move

I have been working in flexdashboards using rbokeh to draw some dynamic graphs. Because this is a bar chart mapped to categorical data in the variable Classification, I am unable to manually create a legend, which is fine because rbokeh does it automatically.
However, I am having some issues with the legend and labeling:
It is placed horribly, I would like to tell r to place in the upper left hand corner to get it away from bars with content.
I would like to drop the red ab_line into the legend and label it (using standard legend = will not work because of the mapped variables in the base chart
This graph needs to be 508 compliant for translation, the flexdashboard is, as well as the bokeh tools on the left hand margin and the keys in the pop ups, but the values and labels remain in English. Does anyone have a way of making the charts responsive to google translate? I am fine if that involves editing the extruded page....I will just need more guidance in doing it there.
figure(title=" Confirmed & Probable Cases by Year",width= 1400, height
=350)%>%
ly_bar(x=Year, y= count, position='stack', data=probConf,
width=.9,hover=TRUE, legend=TRUE, color=Classification) %>%
x_axis(label ='Year')%>%
y_axis(label ='Cases')%>%
ly_abline(v=17.5, legend=NULL, color = "red", width =1, alpha=.5)%>%
[![enter image description here][1]][1]set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
To answer number 1, you can use legend_location to specify the placement of the legend (see example below and note I replaced the probConf data with the lattice barley dataset so that it is reproducible for others).
figure(title = " Confirmed & Probable Cases by Year", width = 1400,
height = 350, legend_location = "top_left") %>%
ly_bar(x = variety, y = yield, position = "stack", data = lattice::barley,
width = 0.9, hover = TRUE, legend = TRUE, color = year) %>%
x_axis(label = "Year") %>%
y_axis(label = "Cases") %>%
ly_abline(v = "Svansota:1", color = "red", width = 1, alpha = 0.5) %>%
set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
#2 is currently difficult to achieve in rbokeh but it should be more robust to situations like this (mixing mapped and user-defined legend entries) in the future. If ly_abline() were to accept data as an argument, you could use use a mapped variable for color to resolve the issue.
One solution that isn't very pretty is to manually draw the bar chart polygons with ly_rect (one call to ly_rect for each classification) and use custom legend entries for those and then add a custom legend entry for ly_abline.
I do not know the answer to #3.

Resources