Plotly rangeslider with quarter dates - r

I would like to draw plotly graphs with rangeslider (including start/end range), yet printing quarter dates on the X-axis, instead of the usual ymd format, as shown in the example below ; i.e. printing "Q1 2019" instead of "Jan 2019" :
library(plotly)
library(zoo)
d <- tibble::tibble(
time = as.yearqtr(seq(as.Date("2016-01-01"), as.Date("2020-08-31"), by = "quarters")),
y = rnorm(seq_along(time))
)
d$time <- as.Date(d$time, format = "%Y-%m-%d")
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19])

You can do this with layout using ticktext and tickvals. This is the code that will ensure you see years and quarters on the X-axis.
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19]) %>%
layout(xaxis = list(ticktext = paste0(c(rep(2018, 3),
rep(2019, 4),
rep(2020, 2)),
" Q",
c(2:4, 1)),
tickvals = d$time[10:18]
))
Using set.seed() makes the code repeatable, (since you used rnorm). I used set.seed(3958) if you wanted to see the same output.
Another way that you can customize the text is through the zoom level. Plotly references this site for the formatting here. There are a few examples on Plotly's website, as well. Check it out.
plot_ly(d, x = ~time, y = ~y) %>%
add_lines() %>%
rangeslider(d$time[10], d$time[19]) %>%
layout(xaxis = list(
tickformatstops = list(
list(dtickrange = list(NULL, "M1"),
value = "%Y %b"),
list(dtickrange = list("M1", "M6"),
value = "%Y Q%q"),
list(dtickrange = list("M6", NULL),
value = "%Y Y")
)))

Related

Group by month to plot on R with Highcharter

I have the following dataset:
xdata <- seq(as.Date("2020-01-01"),as.Date("2020-12-31"), "days")
ydata <- c(1:366)
datamipo <- data.frame(xdata,ydata)
And I want to plot the data by month and plot using highcharter:
datamipo %>%
mutate(month = format(xdata,"%b")) %>%
group_by(month) %>%
summarise(total = sum(ydata)) %>%
hchart(type = "line",
hcaes(x=month, y=total))
But the x axis doesn't recognize the data as dates and put them in alphabetical order. Please, do you know how can I group the date to show the totals by month? Thank you.
I would think about saving this data differently and operate on the actual values. Here you can see an example of such a setting:
df <- data_frame(
time = seq(as.Date("2020-01-01"), as.Date("2020-02-01"), by = 1),
value = sample(1000:2000, size = 32),
dt = datetime_to_timestamp(time)
)
hchart(df, "line", hcaes(dt, value)) %>%
hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d dayview', week = '%d weekview'))
hchart(df, "line", hcaes(dt, value)) %>%
hc_xAxis(type = "datetime", dateTimeLabelFormats = list(day = '%d of %b', week = '%d of %b'))

Plotly animated map not showing countries with NA values

I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:

formatting time axis in rbokeh

I am trying to create a linechart with rbokeh where the x-axis is supposed to show a datetime variable.
Consider the following example:
data <- tibble(
time = as.POSIXct(c("2019-08-27 08:15:00",
"2019-08-27 10:30:00",
"2019-08-27 12:45:00")),
value = c(0.3, 0.6, 0.2)
)
figure(data = data) %>%
ly_lines(x = time,
y = value) %>%
ly_points(x = time,
y = value,
hover = value) %>%
x_axis(label = "Date"
# number_formatter = "numeral",
# format = list(hours = "%d %B %Y")
) %>%
y_axis(label = "Values",
number_formatter = "numeral",
format = list(percent = "0 %")) %>%
y_range(dat = c(0, 1))
This produces the following plot:
Not only does this show the wrong values on the x-axis, they are also formatted in a very inconvenient way.
I have tried changing the format to a more appropriate way by using the format argument (that has been commented out in my example), but this only causes the plot to not even be created anymore.
What is going on here?
Your code worked for me with the format argument. If you want the time included, I would use this:
figure(data = data) %>%
ly_lines(x = time,
y = value) %>%
ly_points(x = time,
y = value,
hover = value) %>%
x_axis(label = "Date",
number_formatter = "numeral",
format = list(hours = "%Y-%m-%d %H:%M:%S")
) %>%
y_axis(label = "Values",
number_formatter = "numeral",
format = list(percent = "0 %")) %>%
y_range(dat = c(0, 1)) %>%
theme_axis("x", major_label_orientation = 45)

Plotly GGplot - plot reponsive

The code output is a plot that I would like it be responsive, to adjust according to window dimension.
Using just ggplot gives me the result desired but I want to use the interactive tooltip of plotly, but when I do the figure is not responsive.
Is there any fix that it could work ? The code is bellow. I really appreciate any help !
library(dplyr)
library(ggplot2)
library(lubridate)
library(plotly)
df <- data.frame(matrix(c("2017-09-04","2017-09-05","2017-09-06","2017-09-07","2017-09-08",103,104,105,106,107,17356,18022,17000,20100,15230),ncol = 3, nrow = 5))
colnames(df) <- c("DATE","ORDER_ID","SALES")
df$DATE <- as.Date(df$DATE, format = "%Y-%m-%d")
df$SALES <- as.numeric(as.character(df$SALES))
df$ORDER_ID <- as.numeric(as.character(df$ORDER_ID))
TOTALSALES <- df %>% select(ORDER_ID,DATE,SALES) %>% mutate(weekday = wday(DATE, label=TRUE)) %>% mutate(DATE=as.Date(DATE)) %>% filter(!wday(DATE) %in% c(1, 7) & !(DATE %in% as.Date(c('2017-01-02','2017-02-27','2017-02-28','2017-04-14'))) ) %>% group_by(day=floor_date(DATE,"day")) %>% summarise(sales=sum(SALES)) %>% data.frame()
TOTALSALES <- ggplot(TOTALSALES ,aes(x=day,y=sales,text=paste('Vendas (R$):', format(sales,digits=9, decimal.mark=",",nsmall=2,big.mark = "."),'<br>Data: ',format(day,"%d/%m/%Y"))))+ geom_point(colour = "black", size = 1)+stat_smooth() +labs(title='TOTAL SALES',x='dias',y='valor')+ scale_x_date(date_minor_breaks = "1 week")
m <- list(
l = 120,
r = 2,
b = 2,
t = 50,
pad = 4
)
TOTALSALES <- ggplotly(TOTALSALES,tooltip = c("text")) %>% config(displayModeBar = F) %>% layout(autosize = F, width = 1000, height = 500, margin = m,xaxis = list(
zeroline = F
),
yaxis = list(
hoverformat = '.2f'
))
TOTALSALES

annotation in highchart doesn't work as expected

I was using Highchart to plot some time series and wanted to add some annotation to the plot to highlight some key points. I knew putting the cursor on the graph can pop up the context, however, some automatic graph generation is needed and hence annotating is the best approach.
And I did that, with the last line in the code below. However, the effect is not what I expected. The text was located at the bottom left corner, not located at the right horizontal position yet the vertical position is right. The time series are created using xts library, which means the horizontal axis is simply the date data structure, nothing fancy. xValue is specified as the 900th element of all the time points which have a total length of 1018, so the 900th time point must be in the second half of the graph.
Anyone knows how I can put the annotation at the right location? Many thanks.
hc <- highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_annotations(list(enabledButtons=FALSE, xValue = index(x)[900], yValue = -5, title =list(text = "Hello world! How can I make this work!")))
hc
The data can be roughly generated using the following script:
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
Let's star with the #kamil-kulig example, this will be a little out of R world but I want to give some justification if you don't mind.
If we see annotations options is not a object but a list of object(s), so in highcharter is implemented the hc_add_annotation function.
Now, you are using a old version of highcharter. Highcharter devlopment version is using v6 of highchartsJS which made some changes: before the annotations.js was a pluging now is included as a module with some changes in the names of arguments.
Example I: Simple
The example by Kamil Kulig is replicated doing:
highchart(type = "stock") %>%
hc_add_annotation(
labelOptions = list(
backgroundColor = 'rgba(255,255,255,0.5)',
verticalAlign = 'top',
y = 15
),
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date("2017/01/02")),
y = 1.5
),
text = "Some annotation"
)
)
) %>%
hc_xAxis(
minRange = 1
) %>%
hc_add_series(
pointStart = start,
pointInterval = day,
data = c(3, 4, 1)
)
Example II: With your data
Be careful in the way you add the x position. Highcharter include a datetime_to_timestamp function to convert a date into a epoch/timestap which is required for highcharts.
library(xts)
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_add_annotation(
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date(index(x)[900])),
y = 1
),
text = "Hello world! How can I make this work!"
)
)
)

Resources