Is there a way to associate dashStyle by group in the highcharter package.
I would like the line with 'forecast' as type to be dashed.
library(highcharter)
# Create sample data frame
sample_df <- data_frame(sku = c(rep("12",40)),
type = c(rep("actuals",20), rep("forecast",20)),
calendar_week = rep(seq(as.Date("2017-09-08"), as.Date("2018-01-23"), by=7),2),
units = round(c(rnorm(11, mean=50, sd=10), rep(0, 9), c(rnorm(20, mean=100, sd=10))),0))
# Create colours vector
custom_colours <- c("#4286f4", "#d66048")
# Chart
hchart(sample_df, "line", hcaes(calendar_week, units, group = type)) %>%
hc_yAxis(title = list(text = "Units")) %>%
hc_xAxis(title = list(text = "Week"), type = "datetime", tickInterval = 7* 24 * 3600 * 1000) %>%
hc_colors(custom_colours)
Also, is it possible to associate colour with a group, for instance using a mutate with ifelse to create a column with the colours in the dataframe?
You can do:
custom_colours <- c("#4286f4", "#d66048")
custom_dashes <- c("Solid", "ShortDashDotDot")
hchart(sample_df, "line", hcaes(calendar_week, units, group = type),
color = custom_colours, dashStyle = custom_dashes) %>%
hc_yAxis(title = list(text = "Units")) %>%
hc_xAxis(title = list(text = "Week"), type = "datetime", tickInterval = 7* 24 * 3600 * 1000)
Related
I am trying to develop a Business Cycle Clock similar to https://kosis.kr/visual/bcc/index/index.do?language=eng.
I've already achieved most of the things I wanted to replicate, but I can't figure it out how to add these traces (for example, in the link above set speed to 10 and trace length to 5 and then click on 'Apply' to understand what I mean).
Does anyone have any idea how to implement it? It would make the "clock" much easier to read. Thanks in advance.
Reprocible example:
library(plotly)
library(dplyr)
library(magrittr)
variable <- rep('A',10)
above_trend <- rnorm(10)
mom_increase <- rnorm(10)
ref_date <- seq.Date('2010-01-01' %>% as.Date,
length.out = 10,by='m')
full_clock_db <- cbind.data.frame(variable, above_trend, mom_increase, ref_date)
freq_aux = 'm'
ct = 'Brazil'
main_title = paste0('Business Cycle Clock para: ', ct)
m <- list(l=60, r=170, b=50, t=70, pad=4)
y_max_abs = 2
x_max_abs = 5
fig = plot_ly(
data = full_clock_db,
x = ~mom_increase,
y = ~above_trend,
color = ~variable,
frame = ~ref_date,
text = ~variable,
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
) %>%
animation_opts( frame = 800,
transition = 500,
easing = "circle",
redraw = TRUE,
mode = "immediate") %>%
animation_slider(
currentvalue = list(prefix = "PerĂodo", font = list(color="red"))
)
fig
Another more elegant solution would be to rely on ggplot2 + gganimate:
library(ggplot2)
library(gganimate)
ggplot(full_clock_db, aes(x = mom_increase, y = above_trend)) +
geom_point(aes(group = 1L)) +
transition_time(ref_date) +
shadow_wake(wake_length = 0.1, alpha = .6)
You cna play with different shadow_* functions to find the one to your liking.
One way would be to use a line plot and repeat points as necessary. Here's an example as POC:
library(dplyr)
library(plotly)
e <- tibble(x = seq(-3, 3, 0.01)) %>%
mutate(y = dnorm(x)) %>%
mutate(iter = 1:n())
accumulate <- function(data, by, trace_length = 5L) {
data_traf <- data %>%
arrange({{ by }}) %>%
mutate(pos_end = 1:n(),
pos_start = pmax(pos_end - trace_length + 1L, 1L))
data_traf %>%
rowwise() %>%
group_map(~ data_traf %>% slice(seq(.x$pos_start, .x$pos_end, 1L)) %>%
mutate("..{{by}}.new" := .x %>% pull({{by}}))) %>%
bind_rows()
}
enew <- e %>%
accumulate(iter, 100)
plot_ly(x = ~ x, y = ~ y) %>%
add_trace(data = e, type = "scatter", mode = "lines",
line = list(color = "lightgray", width = 10)) %>%
add_trace(data = enew, frame = ~ ..iter.new,
type = "scatter", mode = "lines") %>%
animation_opts(frame = 20, 10)
The idea is that for each step, you keep the trace_length previous steps and assign them to the same frame counter (here ..iter.new). Then you plot lines instead of points and you have a sort of trace..
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)
I have a dataframe that looks like the following:
df <- data.frame(date=c("2020-12-11","2020-12-11","2020-12-12"),
typ=c("shirts","sweaters","sweaters")
sold=c(644,3032,407), check.rows = F, check.names = F, stringsAsFactors = F)
df$date <- as.Date(df$date)
All I need is simply a line plot inside my shiny application. This is how I build the plot:
line_text <- paste0("PORT ID: ",df2$typ)
plt <- plot_ly(df, x = ~date, y = ~sold, color = ~Action, connectgaps = TRUE, mode = "lines+markers",
text = line_text) %>% add_lines() %>% layout(showlegend = FALSE)
Now, if I leave the code as is, the x-axis will show as x lables values like "00:00 Dec 11, 2020".
Why?
One thing I tried to adjust it is the following:
plt <- plt %>%
layout(
#title = "Time Series with Custom Date-Time Format",
xaxis = list(
type = 'date',
tickformat = "%Y-%m-%d"
#tickformat = "%d %B (%a)<br>%Y"
))
This yields this new plot.
All I need is simply daily data and two labels on the x-axis.
Any suggestions?
Thank you
You can specify the distance of the ticks in Ploty by setting dtick for your x- or y-axis in your layout.
layout(xaxis=list('dtick' = 60 * 60 * 24 * 1000))
Setting it to 60 * 60 * 24 * 1000, i.e. 86400000 results in a tick every other day.
library('plotly')
df <- data.frame(date=c("2020-12-11","2020-12-11","2020-12-12"),
typ=c("shirts","sweaters","sweaters"),
sold=c(644,3032,407), check.rows = F, check.names = F, stringsAsFactors = F)
df$date <- as.Date(df$date)
line_text <- paste0("PORT ID: ",df$typ)
plot_ly(df, x = ~date, y = ~sold, connectgaps = TRUE, mode = "lines+markers",
text = line_text) %>% add_lines() %>% layout(showlegend = FALSE, xaxis=list('dtick' = 60 * 60 * 24 * 1000))
i would like to build an interactive chart but i'm very new in highcharts, i want to add average line for the data and change the labels of the bars, now per default say "Series 1:" i want to write "Cdays: ", this is my code now
# Load required R packages
library(highcharter)
# Set highcharter options
options(highcharter.theme = hc_theme_smpl(tooltip = list(valueDecimals = 2)))
df <- data.frame(Year=c('2015','2016','2017','2018','2019'),
CD=c(24, 18, 12, 9, 14))
head(df)
hc <- df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080", borderColor = "#702080",
pointWidth = 80) %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = 'Critical Days') %>%
hc
Thanks !!
To add the mean line, try using plotLines in hc_yAxis and set the value to mean(df$CD). You can also adjust the color, add a label, etc. here.
To change the "Series 1" you see when hovering over the bars, you should set the name inside of hchart - in this case, "Cdays".
Other minor changes below - including use of df$Year for x-axis text labels.
df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080",
borderColor = "#702080",
pointWidth = 80,
name = "Cdays") %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = df$Year) %>%
hc_yAxis(
title = list(text = "Cdays"),
plotLines = list(
list(
value = mean(df$CD),
color = "#00FF00",
width = 3,
zIndex = 4,
label = list(
text = "mean",
style = list(color = "#00FF00")
)
)
)
)
Looking at the documentation, tickmarkPlacement, seems to allow the moving of ticks from 'on' to 'between' but with the hchart function I can't seem to get it to work.
Trying to change from this style to this.
library(highcharter)
# Create sample data frame
sample_df <- data_frame(sku = c(rep("12",40)),
type = c(rep("actuals",20), rep("forecast",20)),
calendar_week = rep(seq(as.Date("2017-09-08"), as.Date("2018-01-23"), by=7),2),
units = round(c(rnorm(11, mean=50, sd=10), rep(0, 9), c(rnorm(20, mean=100, sd=10))),0))
# Create colours vector
custom_colours <- c("#4286f4", "#d66048")
# Chart
hchart(sample_df, "line", hcaes(calendar_week, units, group = type), color = custom_colours) %>%
hc_yAxis(title = list(text = "Units")) %>%
hc_xAxis(title = list(text = "Week"), startOfWeek = 5, type = "datetime", tickInterval = 7* 24 * 3600 * 1000, tickmarkPlacement = "between")
tickmarkPlacement works for categorized axes only. Try this:
hchart(sample_df, "line", hcaes(factor(format(sample_df$calendar_week, "%d-%b-%Y")),
units, group = type), color = custom_colours) %>%
hc_yAxis(title = list(text = "Units")) %>%
hc_xAxis(title = list(text = "Week"), tickmarkPlacement = "between")