need some help and would be grateful for any advice. I want to create an interactive treemap in R. So far, so good, so bad. I managed that and was able to create an HTML widget, but when I open it, the legend isn't there anymore. In the original plot it is still there, but not as a saved file. I would be grateful for tips! this is my code:
library(tidyverse) library(readr) library(lubridate) library(ggthemes) library(treemap) library(d3treeR) library(readxl) library(htmlwidgets) df <- read_excel("df.xlsx")
Tidydata <- df %>% group_by(Level1, Level2, Level3) %>% summarise(Count = n())
tree <- treemap(Tidydata, index=c("Level1", "Level2", "Level3") ,vSize="Count" ,vColor="Count", type="value", border.col=c("black","white"), palette = "Greens", title="Treemap",
fontsize.title=16, fontsize.labels = 7, title.legend = "Counts" )
int <- d3tree(tree,width = "200%", height ="600px", rootname = "Level1")
saveWidget(int, file="TreePlot.html", selfcontained = T)
Update: I found out how to resolve the Problem with the missing legend and the overlapping issues.
If you are struggeling with the same issue, please use
int <- **d3tree2**(tree,width = "200%", height ="600px", rootname = "Level1")
instead of
int <- d3tree(tree,width = "200%", height ="600px", rootname = "Level1")
and you can create very nice interactive treemaps.
Related
I'm trying to add separate images to popups so that as you click on each location, an image specific to that place/popup appears. I've figured out how to get one image in, but it applies to all of the popups on the map instead of just one. I have been trying to use the package leafpop for this, but I can't really figure out how to make it work. Even if I just use one image, nothing appears on the map.
This is what my code looks like for it:
library(leaflet)
library(leafpop)
img = system.file("file/image_name.jpg", package = "jpg")
leaflet(map) %>%
addTiles() %>%
addCircleMarkers(label = map#data$name,
weight = 2,
color = "grey",
fillColor = "red",
fillOpacity = 0.7)%>%
addPopupImages(img, group = "map")
I know there's some bits in there that I'm not quite doing right. At this point, I just want to know if it's even possible to do this the way I'm envisioning. Any help is appreciated.
The images need to be in a vector of the same length as the points passed to leaflet. Here is a reproducible example you can copy paste that will get you started:
library(tidyverse)
library(sf)
library(leaflet)
library(leafpop)
pts <- tibble(x = runif(10, 175, 176),
y = runif(10, -38, -37)) %>%
st_as_sf(coords = c("x", "y"), crs = 4326)
img <- glue::glue("https://github.com/IQAndreas/sample-images/blob/gh-pages/100-100-color/{11:20}.jpg?raw=true")
pts$img <- img
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pts, group = "pts") %>%
addPopupImages(pts$img, group = "pts")
Figured it out, with the help of Rich Pauloo! This is the code I ended up using the get local image files. It's a little clunky, but it worked out for me:
data_name <- readOGR("data/map_file.kml")
data_name2 <- data.frame(data_name)
pts <- st_as_sf(data.frame(data_name2),
coords = c("coords.x1", "coords.x2"), crs = 4326)
img <- c("images/picture_name.jpg") ##did this for every image I wanted to use, in the order
##that matched up with the data points I wanted them associated with.
pts$img <- img
leaflet() %>%
addTiles() %>%
addCircleMarkers(data = pts, group = "pts") %>%
addPopupImages(pts$img, group = "pts", width = 300)
Sorry if my conventions for writing out code are not quite right for the website. I just wanted to keep things generic and not include any of my file names or anything.
EDIT
This seems to be an issue already known to the plotly community
github plotly issue #689
and there is an analogous question here on SO.
Unfortunately, it seems no solution is available yet. Any advice would be greatly appreciated.
I am trying to use Crosstalk and Plotly to create a dashboard and I have come across an unexpected behaviour.
When selecting through the Crosstalk filter, the Plotly bargraph leaves "gaps" for the unselected entries.
As a reproducible example, let's say I want to compare cities populations, what I am getting is this (code at the bottom):
It might very well be that I am missing something, is there a way to get rid of the gap? any advice on viable ways to do a similar comparison avoiding the issue?
Thanks in advance.
Code:
---
title: "Crosstalk+Plotly bargraph selection"
---
```{r setup, include=FALSE}
options(stringsAsFactors = FALSE)
library(crosstalk)
library(dplyr)
library(plotly)
#data on cities' population
city_pop <- data.frame("City" = c("Florence", "Milan", "Venice"),
"Population" = c(382258, 1352000, 261905))
#setting up Crosstalk shared data
sd <- SharedData$new(city_pop, key = city_pop$city)
#filter for the cities
filt <- filter_select(
id = "select_name",
label = "Selected City",
sharedData = sd,
group = ~City)
#barplot of cities' population
bars_pop <- plot_ly(sd, x = ~City, y = ~Population) %>%
add_bars(width=0.2,
x = ~City,
y = ~Population,
color = I("#89CFF0"),
name = "",
opacity=.9,
hoverinfo = 'y',
hovertemplate = paste('%{x} <br> number of Residents: %{y}<extra></extra>')
)
```
```{r, echo=FALSE}
filt
bars_pop
```
This worked for me - on the axis where it's happening, set categoryorder = "trace".
e.g.,
plot_ly(...) %>% layout(yaxis = list(categoryorder = "trace"))
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.
I'm working with the ggmap tutorial by Manuel Amunategui over at http://amunategui.github.io/ggmap-example/. It is a wonderful introduction to the ggmap package and thankfully I understand his tutorial.
However, I am also trying to make this material interactive through R markdown. When I run the below document, for some reason the rendering of the map is of very low quality. In my standard .R script the image produced is way better. Any thoughts as to what might cause the drastic difference in quality?
Also, in R Markdown, is it possible to have custom sizing of the images as well as placement? I am specifically interested in making the map larger and/or displaying another map with it side-by-side.
This first block of code is just to get your hands on the data if desired.
#install.packages("RCurl"); install.packages("xlsx"); install.packages("zipcode"); install.packages("ggmap")
library(RCurl)
library(xlsx)
# NOTE if you can't download the file automatically, download it manually at:
#'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/'
urlfile <-'http://www.psc.isr.umich.edu/dis/census/Features/tract2zip/MedianZIP-3.xlsx'
destfile <- "census20062010.xlsx"
download.file(urlfile, destfile, mode="wb")
census <- read.xlsx2(destfile, sheetName = "Median")
#census <- read.xlsx2(file = "census20062010.xlsx", sheetName = "Median")
head(census)
# clean up data
# census <- census[c('Zip','Median..', 'Pop')]
names(census) <- c('Zip','Median', 'Pop')
census$Median <- as.character(census$Median)
census$Median <- as.numeric(gsub(',','',census$Median))
census$Pop <- as.numeric(gsub(',','',census$Pop))
head(census)
# get geographical coordinates from zipcode
library(zipcode)
data(zipcode)
census$Zip <- clean.zipcodes(census$Zip)
census <- merge(census, zipcode, by.x='Zip', by.y='zip')
census$location <- paste0(census$city, ", ", census$state)
names(census) <- sapply(names(census), tolower)
# saved census to census.rdata at this point...
The next chunk of code below is what is in the markdown file.
```{r, message=FALSE, echo=FALSE}
library(ggmap)
library(ggplot2)
load("census.rdata")
inputPanel(
textInput("loc", label = "Location", value = "Orlando, FL"),
sliderInput("zoom", label = "Zoom Level",
min = 1, max = 12, value = 10, step = 1)
)
renderPlot({
census2 <- census[census$location == input$loc,]
map <- get_map(location = input$loc,
zoom = input$zoom,
maptype = 'roadmap',
source = 'google',
color = 'color',
filename = "ggmapTemp")
print(ggmap(map) +
geom_point(
aes(x=longitude, y=latitude,
show_guide = TRUE, size=Median),
data=census2, colour = I('red'), na.rm = T)
)
})
```
Thanks for your help!