Shiny with plotly - r

I'm creating a notebook with shiny and i have found the following issue when using the add-on plotly:
Data_xts=Data_xts() #this return a reactive data.frame. fm_timeseries is already formated as POSIXct and has the following format : YYYY-MM-DD hh:mm:ss
plot_ly(x=Data_xts$fm_timeseries, y = Data_xts$Open,name='Stock Prices',showlegend = FALSE) %>%
add_trace(x=Data_xts$fm_timeseries, y = Data_xts$UKX_open, yaxis='y2') %>%
add_trace(x=Data_xts$fm_timeseries, y = Data_xts$TotalNews, yaxis='y3') %>%
layout(yaxis=list(title='Stock Price'),
yaxis2=list(title='Market Index', overlaying = "y",side='right',position=.97,tickfont = list(size = 8)),
yaxis3=list(title='Total News', overlaying = "y",side='right',anchor='free', tickfont = list(size = 8),position=1),
xaxis=list(title='Time Series') , showlegend = TRUE)
Here is a couple of issues I'm founding:
Time stamp don't show as timestamp (I even tried the simple example from plotly and R and verified that it doesn't work on Shiny). In fact timestamp is categorize as string and the xaxis tittle can't be seen as a result of this.
Challenges getting the yaxis2 and 3 in the same axes without overlapping with the chart itself.
To solve this wonder if there is a format that we can pass into the xaxis (tried type='date' but didn't work) and if there is any type of auto-arrange on the yaxis on the right (2 and 3).

Try using "factor".
So in your example:
plot_ly(x= ~factor(Data_xts$fm_timeseries), y = ~Data_xts$Open, name='Stock Prices',showlegend = FALSE)

Related

Plotly gauge graph and crosstalk filtering for flexdashboard

I am trying the create a plotly gauge graph for a flexdashboard which should change value depending on the chosen filter in crosstalk::filter_select().
I have tried and tried but cannot get the filter to work. This is an example with mtcars of what I am trying to do. I noticed that if the SharedData object has only one value, then it works, but otherwise plotly does not show any data.
mtcars_data <- tibble::rownames_to_column(mtcars, "Car")
shared_mtcars <- SharedData$new(mtcars_data)
row1 <- bscols(filter_select("Car", "Car", shared_mtcars, ~Car, multiple = F)
)
fig <- plot_ly(shared_mtcars,
domain = list(x = c(0, 1), y = c(0, 1)),
value = ~mpg,
title = list(text = "MPG"),
type = "indicator",
mode = "gauge+number")
bscols(row1, fig, widths = 12)
This code results in a graph with no data. If I subset mtcars_data to take the first row or the first two rows (which happen to have the same value for mpg) then it works. If I subset rows 1 and 3, it doesn't.
I might be missing something - in that case would really appreciate any feedback.

Multiple y-axes in shiny app w/ highcharter

I'm trying to render a graph in a shiny app using highcharter that shares an x-axis (days) but has multiple y-axes (a percent and a count). After some research it seems like I should use the 'hc_yAxis_multiples' method. On the left y-axis, I have % displayed. On the right y-axis, I want the count displayed. There is a line graph that is based on the left y-axis (%), and a stacked bar graph that is displayed based on the right y-axis.
I have been able to overlay the two graphs, but the bar chart portion based on the right y-axis is not formatted to the corresponding y-axis. Based on what I have been looking at, it seems like something like this would produce a result that I want:
##This first block is to show what the data types of the variables I'm using are and what the structure of my df looks like
df$inbox_rate <- df$total_inbox / df$total_volume
df$inbox_rate <- round((df$inbox_rate*100),0)
df$received_dt <- as.character(df$received_dt)
df$received_dt <- as.Date(df$received_dt, "%Y%m%d")
df <- df[order(df$received_dt),]
## This second block here is where I'm trying to build the chart with two Y-axes
hc <- highchart()%>%
hc_title(text = paste(domain_name,sep=""),align = "center") %>%
hc_legend(align = "center") %>%
hc_xAxis(type = "datetime", labels = list(format = '{value:%m/%d}')) %>%
hc_yAxis_multiples(list(title = list(text = "IPR"),labels=list(format = '{value}%'),min=0,
max=100,showFirstLabel = TRUE,showLastLabel=TRUE,opposite = FALSE),
list(title = list(text = "Total Subscribers"),min=0,max = max(df$total_users),
labels = list(format = "{value}"),showLastLabel = FALSE, opposite = TRUE)) %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_add_series(df,"column",hcaes(
x=received_dt,y=total_users,group=isp,yAxis=total_users)) %>%
hc_add_series(df,type="line",hcaes(
x=received_dt,y=inbox_rate,group=isp,yAxis=inbox_rate)) %>%
hc_exporting(enabled = TRUE) %>%
hc_add_theme(thm)
hc
However this produces something that looks like this.
To give more insight about the data I'm using, the domain_name is a string variable that looks like this: example.com. The total_users variable is a number that varies from 0 to about 50000. The received_dt variable is a date, formatted using as.Date(df$received_dt, "%Y%m%d"). The inbox_rate variable is a percent, from 0 to 100.
The bar counts are all displaying to the full height of the graph, even though the values of the bars vary widely. To reiterate, I want the right y-axis that the bar chart heights are based on to be the count of the df$total_users. Within the hc_yAxis_multiples function, there are two lists given. I thought that the first list gives the left y-axis, and the second gives the right. The closest answer to my question that I could find was given by this stackoverflow response
If anyone has any insight, it would be very much appreciated!
Your use of the yAxis statement in hc_add_series seems to be off. First, it should not be inside hcaes and second, it's a number specifying which axis (in order of appearance in hy_yAxis_multiple call) the series belongs to. So hc_add_series(..., yAxis = 1) should be used to assign a series to the second (right) axis.
Below is a (fully self-explaining, independent, minimal) example that shows how it should work.
library(highcharter)
df <- data.frame(
total_inbox = c(2, 3, 4, 5, 6),
total_volume = c(30, 30, 30, 30, 30),
total_users = c(300, 400, 20, 340, 330),
received_dt = c("20180202", "20180204", "20180206", "20180210", "20180212"),
isp = "ProviderXY"
)
df$inbox_rate <- df$total_inbox / df$total_volume
df$inbox_rate <- round((df$inbox_rate*100),0)
df$received_dt <- as.character(df$received_dt)
df$received_dt <- as.Date(df$received_dt, "%Y%m%d")
df <- df[order(df$received_dt),]
hc <- highchart()%>%
hc_xAxis(type = "datetime", labels = list(format = '{value:%m/%d}')) %>%
hc_yAxis_multiples(list(title = list(text = "IPR"),labels=list(format = '{value}%'),min=0,
max=100,showFirstLabel = TRUE,showLastLabel=TRUE,opposite = FALSE),
list(title = list(text = "Total Subscribers"),min=0,max = max(df$total_users),
labels = list(format = "{value}"),showLastLabel = FALSE, opposite = TRUE)) %>%
hc_plotOptions(column = list(stacking = "normal")) %>%
hc_add_series(df,type="column",hcaes(x=received_dt,y=total_users,group=isp),yAxis=1) %>%
hc_add_series(df,type="line",hcaes(x=received_dt,y=inbox_rate,group=isp))
hc
Maybe take this as an example how code in questions should be like. Copy-Paste-Runnable, no outside variables and minus all the things that dont matter here (like the theme and legend for example).

plotly in R: adding labels to surface area charts through layout?

I'm working with surface area charts in plotly and I'm wondering how to change the labels as the process seems different from flat charts so I'm having trouble wrapping my head around how they layout should be arranged. I'm getting a warning message but I see that the title label has gone through, wondering how to get the X axis and Y axis to change. Below is my reproducible code using he built in data set freeny:
#stack question for surface plot
library(plotly)
library(zoo)
#set data
master = freeny
master$year = round(as.numeric(row.names(master)))
master$month = sample(1:6, 39, replace=TRUE)
master$month = paste0("0",master$month)
master$date = as.Date(with(master, paste0(year,"-" ,month,"-" ,"28")))
master$weekday = weekdays(master$date)
master$month_year = as.yearmon(master$date)
master
#build matrix
matrix_d = xtabs(income.level ~ month_year + weekday, master)
matrix_d
#plot
p = plot_ly(z = ~matrix_d) %>% add_surface()
p
#label
p = layout(p, # all of layout's properties: /r/reference/#layout
title = "income levels across month and weekdays", # layout's title: /r/reference/#layout-title
xaxis = list( # layout's xaxis is a named list. List of valid keys: /r/reference/#layout-xaxis
title = "weekday", # xaxis's title: /r/reference/#layout-xaxis-title
showgrid = F # xaxis's showgrid: /r/reference/#layout-xaxis-showgrid
),
yaxis = list( # layout's yaxis is a named list. List of valid keys: /r/reference/#layout-yaxis
title = "month_year" # yaxis's title: /r/reference/#layout-yaxis-title
),
zaxis = list(
title = "income_level"
))
p
Warning message:
'layout' objects don't have these attributes: 'zaxis'
Valid attributes include:
'font', 'title', 'titlefont', 'autosize', 'width', 'height', 'margin', 'paper_bgcolor', 'plot_bgcolor', 'separators', 'hidesources', 'smith', 'showlegend', 'dragmode', 'hovermode', 'xaxis', 'yaxis', 'scene', 'geo', 'legend', 'annotations', 'shapes', 'images', 'updatemenus', 'ternary', 'mapbox', 'radialaxis', 'angularaxis', 'direction', 'orientation', 'barmode', 'bargap', 'mapType'
EDIT FOLLOWUP:
Posted the answer below to the top question but as a followup how would I add values to the tick marks? I'm assuming there is a way to feed a list vector of ordinal values to the ticks such as c("0" = "sunday", "1" = "Monday" . . . ). Is this accurate?
Appreciate the help!!!
Found the answer from a different posting in case anyone ever needs it. I'm wondering though how to add the specific month and weekday to the tick marks?
p <- plot_ly(z = ~matrix_d) %>% add_surface() %>%
layout(title = 'income levels across month and weekdays',
scene = list(xaxis = list(title = 'weekday'),
yaxis = list(title = 'month'),
zaxis = list(title = 'income_level')))
p

How to set dataLabel Format and axis label angle in R highcharter package

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}%'))

Can I include tooltips in the d3pie rcharts implementation?

I am creating a d3pie graph with rcharts following this article.
I am able to create the pie chart and now I would like to add a tooltip similar to this one.
My code so far is:
require(magrittr)
require(dplyr)
require(rCharts)
df<-data.frame(label=c("group1","group2","group3"),value=c(1,5,4),
stringsAsFactors = FALSE)
pie1<-rCharts$new()
pie1$setLib("http://timelyportfolio.github.io/rChartsExtra/d3pie")
pie1$params$chartspec <- list(header = list(title = list(text = "Title"),
subtitle = list(text = "Subtitle")),
data = list(content = df),
labels = list(lines = list(style = "straight")),
tooltips=list(enabled=TRUE,type= "placeholder",
string="{label}"))
pie1
I am not sure if including the tooltips is possible with rcharts.
If it is possible my guess is that the problem comes from the enabled=TRUE. I also tried: enabled="[true]", enabled="{true}" and enabled=T. None of them seem to work.
I am starting to learn d3.js, however, I want to embed the chart in rmarkdown so I would prefer a solution based on R.

Resources