I am struggling in adding one level drilldown in my grouped column chart made using highcharter. To explain, I am taking using the "vaccines" dataset available in highcharter library :
My code (similar) that creates the grouped column chart :
library (highcharter)
library(dplyr)
df <- na.omit(vaccines[vaccines$year %in% c("1928", "1929"),])
df <- ddply(df, c("state", "year"), summarise, count = sum(count))
hc <- hchart(df, type = "column", hcaes(x = state, y = count, group = year)) %>%
hc_xAxis(title = list(text = "States")) %>%
hc_yAxis(title = list(text = "Vaccines")) %>%
hc_chart(type = "Vaccines", options3d = list(enabled = TRUE, beta = 0, alpha = 0)) %>%
hc_title(text = "Demo Example") %>%
hc_subtitle(text = "Click on the on Year to see the Vaccine drill down")
hc
It creates this grouped chart perfectly
I now want to add one level drill down to the chart where I can select the "Year" and corresponding drill down data of the vaccine selected is presented. Can you please help with the best/easiest way to do it considering I have the individual drill down data also in data frames.
Regards,
Nikhil
Related
I'm producing a set of charts using highcharter. I have items, which each have variants, and units sold by variant. I'm looking for a method by which I can choose which variants are pre-selected to appear on the chart.
Below is an example of the chart I produced:
library(tidyverse)
library(highcharter)
library(viridis)
df <- tibble(item_name = c('beer','beer','soft drink','soft_drink'),
units = c(15,50,25,10),
variant_name = c('blonde','white','coke','lemonade'))
cols = as.vector(scales::viridis_pal(option = "turbo", direction = 1)(length(unique(df$variant_name))))
df %>%
group_by(item_name) %>%
arrange(desc(units)) %>%
ungroup() %>%
hchart(
"column", hcaes(x = item_name, y = units, group = variant_name),
stacking = "normal"
) %>%
hc_colors(c(cols))
I would like to be able to pre-select, let's say 'blonde' and 'coke'. Other variants would have to be selected by clicking on the variant name in the chart:
I haven't been able to find a way to do that so far, the documentation for highcharts only points to doing so when you have multiple series.
You could write your own JS function to load the elements. Where you can specify the chart.series.load, check this link for extra info. Here is a reproducible example:
library(tidyverse)
library(highcharter)
library(viridis)
df <- tibble(item_name = c('beer','beer','soft drink','soft_drink'),
units = c(15,50,25,10),
variant_name = c('blonde','white','coke','lemonade'))
cols = as.vector(scales::viridis_pal(option = "turbo", direction = 1)(length(unique(df$variant_name))))
df %>%
group_by(item_name) %>%
arrange(desc(units)) %>%
ungroup() %>%
hchart(
"column", hcaes(x = item_name, y = units, group = variant_name),
stacking = "normal"
) %>%
hc_chart(events = list(load = JS("function() {
var chart = this;
chart.series[1].setVisible(true)
chart.series[2].setVisible(false)
chart.series[3].setVisible(false)
chart.series[4].setVisible(false)
}"))) %>%
hc_colors(c(cols))
Output:
when doing a job I have found a problem that I don't know how to solve.
I have a data frame that has 2 columns:
date
value
And it has a total of 1303 rows.
For each date there are 12 values (1 for each month), except in the last year that only has 7
The work I have to do would be to create a 'drilldown' style chart using the 'highcharter' library. The problem is that I don't know how to do it efficiently.
The solution that comes to my mind is not very efficient, below I show my solution so you can see what I mean.
dataframe
# Load packages
library(tidyverse)
library(highcharter)
library(lubridate)
# Load dataset
df <- read.csv('example.csv')
# Prepare df to use
dfDD <- tibble(name = year(df$date),
y = round(df$value, digits = 2),
drilldown = name)
# Create a data frame to use in 'drilldown' (for each year)
df1913 <- df %>%
filter(year(date) == 1913) %>%
data.frame()
df1914 <- df %>%
filter(year(date) == 1914) %>%
data.frame()
# Create a drilldown chart using Highcharter library
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Example Drilldown") %>%
hc_xAxis(type = "category") %>%
hc_legend(enabled = FALSE) %>%
hc_plotOptions(series = list(boderWidth = 2,
dataLabels = list(enabled = TRUE))) %>%
hc_add_series(data = dfDD,
name = "Mean",
colorByPoint = TRUE) %>%
hc_drilldown(allowPointDrilldown = TRUE,
series = list(list(id = 1913,
data = list_parse2(df1913)),
list(id = 1914,
data = list_parse2(df1914))))
Seeing my solution for the first time, I realized that in order to complete the graph I would have to create a subset of values for each year. Having realized that I tried to find a more efficient solution using a 'for loop' but so far I can't get it to work.
Is there a more efficient way to create this graph using a 'loop'!?
If it can be done in another way than using loops, I would also like to know.
Thank you for reading my question and I hope I explained myself well.
Using split and purrr::imap you could split your data by years and loop over the resulting list to convert your data to the nested list object required by hc_drilldown. Note: It's important to make the id a numeric and to pass a unnamed list.
library(tidyverse)
library(highcharter)
library(lubridate)
series <- split(df, year(df$date)) %>%
purrr::imap(function(x, y) list(id = as.numeric(y), data = list_parse2(x)))
# Unname list
names(series) <- NULL
highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Example Drilldown") %>%
hc_xAxis(type = "category") %>%
hc_legend(enabled = FALSE) %>%
hc_plotOptions(series = list(boderWidth = 2,
dataLabels = list(enabled = TRUE))) %>%
hc_add_series(data = dfDD,
name = "Mean",
colorByPoint = TRUE) %>%
hc_drilldown(allowPointDrilldown = TRUE,
series = series)
I am using highcharter library and referred to below link to create an interactive tooltip chart in a bubble chart
https://jkunst.com/blog/posts/2019-02-04-using-tooltips-in-unexpected-ways/
Plot image:
Using gapminder data as shown in link I was able to reproduce the same but when I use my other data then the tool tip chart doesn't appear.
Code for my other data:
libs
library(tidyverse)
library(highcharter)
data
grouped_cases_df <- read.csv("https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/grouped_cases.csv")
tt_base <- grouped_cases_df %>%
arrange(desc(Date)) %>%
distinct(Country.Region, .keep_all = TRUE)
tt_base
tt_inner <- grouped_cases_df %>%
select(Country.Region, Date, Daily_cases) %>%
nest(-Country.Region) %>%
mutate(
data = map(data, mutate_mapping, hcaes(x = Date, y = Daily_cases), drop = TRUE),
data = map(data, list_parse)
) %>%
rename(tt_nestdata = data)
tt_inner
tt_daily <- left_join(tt_base, tt_inner, by = "Country.Region")
tt_daily
hchart(
tt_daily,
"point",
hcaes(x = Active, y = Confirmed, name = Country.Region,
size = Daily_cases, group = continent, name = Country.Region)
) %>%
hc_yAxis(type = "logarithmic") %>%
hc_tooltip(
useHTML = TRUE,
headerFormat = "<b>{point.key}</b>",
pointFormatter = tooltip_chart(accesor = "tt_nestdata")
) %>%
hc_title(text = "Active Vs Confirmed Cases as of latest Date") %>%
hc_subtitle(text = "Size of bubble based on Deaths <br> (ttchart: population growth)")
Issue: Getting blank tooltip chart for every country.
I also tried by changing Country.Region to as.factor() but didn't help. I am not sure whats wrong with this.
It's needed make two changes:
The tooltip data needs to be ready to highcharter. So you need to transform the Date column from text to date then to a numeric value which highcharts can interpret as date:
mutate(Date = highcharter::datetime_to_timestamp(lubridate::ymd(Date)))
Then, in the hc_opts argument in the tooltip_chart function you need to specify the x Axis treat the values as date.
pointFormatter = tooltip_chart(accesor = "tt_nestdata", hc_opts = list(xAxis = list(type = "datetime")))
Then:
I'm trying to create a line chart using highcharts package with a time series dataframe that is similar to this one:
reprexDF <- data.frame(category = c("apples","oranges","bananas","limes"),
month1 = c(5,8,10,2),
month2 = c(NA,7,2,3),
month3 = c(NA, NA, 10,2),
month4 = c(11,12,5,9)
)
I want each row to be a separate line on the line chart that shows the trend for each category across months, all plotted on the same chart.
I tried parsing each row into a list with:
reprexDF <- highcharter::list_parse2(reprexDf)
and then attempting to plot with:
highchart() %>%
hc_plotOptions(line = list(marker = list(enabled = FALSE)))%>%
hc_add_series_list(reprexDF)
but I'm still not being able to plot this data.
I just really want to avoid having to hard code each series because the lists are supposed to be dynamic.
Would first convert your data frame to long. Then you can group_by category and use list_parse2 to make lists by category.
For this plot, I made sure month was numeric on x-axis. I renamed category to name so it would show up in legend and labels. And added connectNulls in case you wanted to connect points across missing values (NA).
library(highcharter)
library(tidyverse)
reprexDF2 <- reprexDF %>%
pivot_longer(cols = -category, names_to = "month", values_to = "value", names_pattern = "month(\\d)$") %>%
group_by(category) %>%
do(data = list_parse2(data.frame(as.numeric(.$month), .$value))) %>%
ungroup() %>%
rename(name = category)
highchart() %>%
hc_plotOptions(series = list(connectNulls = TRUE), line = list(marker = list(enabled = FALSE)))%>%
hc_add_series_list(reprexDF2)
I'm building a shiny app that displays actual vs planned expenditure on a monthly basis. I've created controls that allow the user to select a specific project. But in some projects, there are only planned expenditure for a single month is there. For those projects, the Date is not coming properly on the X-Axis.
He is the code that I've written:
renderHighchart({
highchart() %>%
hc_chart(type = "column") %>%
hc_xAxis(categories = planned_vs_actual()$documentDate, title = list(text = "<b>Date</b>"), type = "datetime") %>%
hc_add_series(name="Planned Expenditure",
data = planned_vs_actual()$PlannedExpenditure) %>%
hc_add_series(name="Actual Expenditure",
data = planned_vs_actual()$ActualExpenditure) %>%
hc_tooltip(borderWidth = 1.5,
pointFormat = paste('<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>')) %>%
hc_legend(enabled = TRUE) %>%
hc_title(text = "Planned vs Actual Expenditure (In Crores)") %>%
hc_subtitle(text = dataPeriod) %>%
hc_yAxis(title = list(text = "<b>Amount <br>(In Crores)</br></b>"))%>%
hc_add_theme(custom_theme)
})
Finally found the solution on this link: https://github.com/jbkunst/highcharter/issues/395
Just need to make this change:
hc_xAxis(categories = as.list(planned_vs_actual()$documentDate), title = list(text = "<b>Date</b>"), type = "datetime")
Put the date in as.list() function to show it properly on x-axis.