Setting Order of R Highcharter Categories - r

I noticed that my bar graphs change in order based on alphabetical order. I'm using a selectinput, thus if a person who is selected with a name beginning in A, they are at the top, but if it is a letter after C, then they move to the bottom. This is not based on the value of the bars, but seems tied to the names. How can I keep the ProviderName at top always?
My hc code is below
hchart(
comparison_prov_df,
type = "bar",
hcaes(x = Metric, y = Value, group = ProviderName),
colorByPoint = F,
showInLegend = T,
dataLabels = list(enabled = T)
) %>%
hc_chart(zoomType = "xy") %>%
hc_tooltip(crosshairs = TRUE, shared = FALSE, borderWidth = 1) %>%
hc_credits(
enabled = TRUE,
text = ""
) %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_legend(enabled = TRUE) %>%
hc_exporting(
enabled = TRUE,
filename = "data"
) %>%
hc_title(
text = "Title",
align = "left"
) %>%
hc_yAxis(
title = list(text = "Y Axis"),
labels = list(
reserveSpace = TRUE,
overflow = "justify"
)
) %>%
hc_xAxis(title = "") %>%
hc_tooltip(pointFormat = "{point.y:.1f}")

I am not sure what the original data is like, but I'll provide a simple example of one way to change the order of items on an axis. You can change the order by simply using hc_xAxis and then listing the category order.
library(highcharter)
library(tidyverse)
df %>%
hchart("bar", hcaes(x = category, y = value, group = group)) %>%
hc_xAxis(
categories = list(
"Pineapples",
"Strawberries",
"Apples",
"Plums",
"Blueberries",
"Oranges"
)
)
Output
Data
set.seed(326)
df <-
data.frame(category = rep(c(
"Apples", "Oranges", "Plums", "Pineapples", "Strawberries", "Blueberries"
), each = 2),
value = round(runif(12, min = 0, max = 100)),
group = rep(c(2020, 2021), 6))

Related

Highcharter format number in tooltip

I'm using Highcharts in R, and I want to format the number in the tooltip as a currency without decimal spaces. Right now, numbers appear like this: 34 537 987.21. I want that number to look like this: $34,537,987. Or, better yet, like this: $34M.
Here's a sample of my code:
highchart() %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = data)
) %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = other_data)
) %>%
hc_plotOptions(series = list(marker = list(enabled = TRUE,
hover = TRUE,
symbol = 'circle'))
) %>%
hc_tooltip(
shared = TRUE,
crosshairs = TRUE
)
Use the tooltip parameter inside hc_ad_series() and define as shown below.
highchart() %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = data),
tooltip = list(pointFormat = "$ {point.data}")
) %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = other_data),
tooltip = list(pointFormat = "$ {point.other_data}")
) %>%
hc_plotOptions(series = list(marker = list(enabled = TRUE,
hover = TRUE,
symbol = 'circle'))
)
Hope it helps.

Highcharter-R: x-axis values not showing up, wrong text on y-axis

I am trying to create a mixed chart with highcharter R, see below the full code. I can't get rid of the following problems:
how to delete the text "Values" on both y-axes? I'd like only my text to show up ("xxx" and "yyy").
why are the x-axis values not showing up (2019, 2020a, 2020b) and instead below the columns "1", 2" and "3" appear? How could I change it?
Any help would be appreciated, thank you!
df2 <- data.frame(supp=rep(c("Media", "Mediana"), each=3),
Anno=rep(c("2019", "2020a", "2020b"),2),
Reddito=c(40100, 39000, 38000, 34000, 33000, 32000))
df3<-data.frame(supp=rep(c("Numero indice media", "Numero indice mediana"), each=3),
Anno=rep(c("2019", "2020a", "2020b"),2),
Reddito=c(100, 97, 96, 100, 96, 95))
highchart() %>%
hc_yAxis_multiples(
list(title = list(text = "xxx"),opposite=F),
list(title = list(text = "yyy"),opposite=TRUE),
list(lineWidth = 0),
list(showLastLabel = F, opposite = T))%>%
hc_add_series(data = df2,type="column" ,hcaes(x = "Anno", y = 'Reddito', group = 'supp')) %>%
hc_add_series(data = df3, type = "spline", hcaes(x = 'Anno', y = 'Reddito', group = 'supp'),yAxis = 1)
To answer your first question, try this:
library(highcharter)
highchart() %>%
hc_yAxis_multiples(
list(title=list(text="xxx",margin = 20),
lineWidth = 3,showLastLabel = FALSE,opposite = FALSE),
list(
title=list(text="yyy", margin = 20),
lineWidth = 3,showLastLabel = FALSE, opposite = T)
) %>%
hc_add_series(data = df2,type="column" ,hcaes(x = "Anno", y = 'Reddito', group = 'supp')) %>%
hc_add_series(data = df3, type = "spline", hcaes(x = 'Anno', y = 'Reddito', group = 'supp'),yAxis = 1)
Values of xAxis aren't displayed in the way you expect, because you didn't define xAxis type, so they appear as index numbers by default. If you specify the type within hc_xAxis to category, it should work fine. Here's the final code:
library(highcharter)
highchart() %>%
hc_yAxis_multiples(
list(title=list(text="xxx",margin = 20),
lineWidth = 3,showLastLabel = FALSE,opposite = FALSE),
list(
title=list(text="yyy", margin = 20),
lineWidth = 3,showLastLabel = FALSE, opposite = T)
) %>%
# Specify Type
hc_xAxis(type = "category") %>%
hc_add_series(data = df2,type="column" ,hcaes(x = "Anno", y = 'Reddito', group = 'supp')) %>%
hc_add_series(data = df3, type = "spline", hcaes(x = 'Anno', y = 'Reddito', group = 'supp'),yAxis = 1)

Is there a reason my plotly dropdown menu doesn't update data appropriately?

I'm working with plotly for the first time to create an interactive chart that can plot any variable from the R tidykids package as a time series grouped by state. Here's my code to format the data frame object as I have it in my plotly chain.
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
kids_my_variables <- kids %>% pivot_wider(id_cols = c('state','year') , names_from = 'variable' , values_from = 'inf_adj') %>% mutate(fips = fips(state), total = rowSums(.[3:25], na.rm = TRUE), education_agg = PK12ed + highered + edsubs + edservs + pell + HeadStartPriv, education_pcnt = (round(education_agg / total, 2)*100) , lib_pcnt = ((lib / total)*100) , park_pcnt = (round(parkrec / total,2))*100) %>% select(fips, state, year, education = education_pcnt, libraries = lib_pcnt, `parks & rec` = park_pcnt, total) %>% filter(year != 1997)
Here's my plotly chain.
plot_ly(kids_my_variables, x = ~year) %>%
add_lines(y = ~education, color = ~state) %>%
add_lines(y = ~`parks & rec`, color = ~state, visible = FALSE) %>%
layout(
title = "% of total child spending",
showlegend = TRUE,
updatemenus = list(
list(
buttons = list(
list(method = "restyle",
args = list(list(visible = list(TRUE, FALSE)),
list(yaxis = list(title = "Education"))),
label = "Education"),
list(method = "restyle",
args = list(list(visible = list(FALSE, TRUE)),
list(yaxis = list(title = "Parks & Rec"))),
label = "Parks & Rec")))
)
)
When I use the dropdown menu to change my plotted data, it retains data from the original plot afterwards. The range of the y-axis for education s/b from 25-69. Parks and rec on the other hand s/ from 1-7, but the using the dropdown filter to update the plot to parks and rec give me this.
link to image cause I'm not cool enough to embed yet
It's a quirk in plotly that it expects you to set visible to TRUE or FALSE for each level of your grouping variable (i.e. state).
Concatenating two rep()s (one for true, one for false) for the number of states seems to be the only workaround I can find for now.
You also need to use method = "update" instead of restyle as you're changing both data and layout (y-axis title).
This should work:
plot_ly(kids_my_variables, x = ~year) %>%
add_lines(y = ~education, color = ~state) %>%
add_lines(y = ~`parks & rec`, color = ~state, visible = FALSE) %>%
layout(
title = "% of total child spending",
showlegend = TRUE,
updatemenus = list(
list(
buttons = list(
list(method = "update",
args = list(list(visible = c(rep(TRUE, length(unique(kids_my_variables$state))), rep(FALSE, length(unique(kids_my_variables$state))))),
list(yaxis = list(title = "Education"))),
label = "Education"),
list(method = "update",
args = list(list(visible = c(rep(FALSE, length(unique(kids_my_variables$state))), rep(TRUE, length(unique(kids_my_variables$state))))),
list(yaxis = list(title = "Parks & Rec"))),
label = "Parks & Rec")))
)
)

highcharter hc_axis not working correctly

Follow up on this post I am not able to get the x-axis labels in correct format using the code below.
hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_xAxis(categories = allDates$VisitDate, title = list(text = 'Deadline'), type = 'datetime', dateTimeLabelFormats = list(month = "%b", year = "%y")) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
)
The resulting chart below has labels all messed up.
Also is it possible to specify interval as in 1 month, 15 days etc.
hchart(visits, "column", hcaes(x = VisitDate, y = freq, group = Clinic)) %>%
hc_xAxis(categories = allDates$VisitDate, title = list(text = 'Deadline'), type = 'datetime', dateTimeLabelFormats = list(month = "%b", year = "%y")) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
)
You need to add hcaes inside the hchart function. There are some nice examples here Highcharter page
Also Highchart prefer dates as timestamp to work the way you want, please check this answer plotband.
I hope this help you. Have a nice day
edit1:
With this code you can add the select range to date you want, however I think to this kind of data and chart it does not apply
hchart(visits, "column", hcaes(x = VisitDate, y = freq, group = Clinic))%>%
hc_xAxis(categories = allDates$VisitDate, title = list(text = 'Deadline'),
type = 'datetime', dateTimeLabelFormats = list(month = "%b", year = "%y"))
%>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
) %>%
hc_rangeSelector(enabled = TRUE, buttons = list(
list(type = "all", text = "All"),
list(type = "month", count = 1, text = "1m"),
list(type = "day", count = 15, text = "15d"),
list(type = "day", count = 1, text = "1d")
), selected = 3)

Displaying datatable in highcharter tooltip

Using the first block of code in this post I want to create a tooltip that would display the list of doctors visiting a clinic on a particular day.I tried the following code which displays nothing
library(DT)
tltp = DT:: datatable(data.frame(Doctors = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]))
hc%>%hc_tooltip(pointFormat = tltp)
I also tried using the tooltip_table which gives error
tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
hc%>%hc_tooltip(pointFormat = tltp)
Error: unexpected symbol in:
"tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
tltp"
Apologies I am not fluent in writing javascript.
As the official page recommend, to use highcharter is good alternative read how highchartsjs works. So, see this example with a simple custom tooltip.
hc <- hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
)
Adding the simple tooltip using the column names: Clinic and freq
hc %>%
hc_tooltip(pointFormat = "this is and clinic {point.Clinic} and freq {point.freq}")
The tooltip_table function is to make tables in the tooltip:
tt <- tooltip_table(c("Clinic", "Freq"), c("{point.series.name}", "{point.y}"))
hc %>%
hc_tooltip(pointFormat = tt, useHTML = TRUE)
If you need other data to show in the tooltip you can create the columun:
visits$doctors <- sample(letters, size = nrow(visits))
And then create the chart again (using the new data) and use this column in the tooltip:
hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
) %>%
hc_tooltip(pointFormat = "Here is the doctor {point.doctors}")

Resources