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

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

Related

I am trying to figure out how to create custom tooltips that show up when hovering over an axis label in highcharter in R

This jsfiddle example shows what I am trying to do in highcharter in r:
http://jsfiddle.net/key2xanadu/zfsfz0c9/
Here is a very simple example that I am trying to get to work in R:
x <- c(0,1)
y <- c(29.9, 71.5)
data <- cbind(x,y)
data <- as.data.frame(data)
data %>%
hchart('line', hcaes(x = x, y = y)) %>%
hc_xAxis(
labels = list(
enabled = TRUE,
categories = c('one', 'two'),
formatter = JS("function(){
$('document').ready(function () {
$('#text_title').tooltip({placement: 'bottom', title:'HELLO TITLE!'});
$('#label_one').tooltip({placement: 'bottom', title:'HELLO ONE!'});
$('#label_two').tooltip({placement: 'bottom', title:'HELLO TWO!'});
});
}"
),
useHTML = TRUE
)
)
I am missing something though because it is not showing the xaxis labels or a tooltip that I want to show up when I hover. Any insight would be so much appreciated!

Highcharts X axis categories name gets only shows 1 character

I created a column and line chart with highcharts.
X axis category names have been appearing fine in other charts created with the same code but now I encounter an issue where the entire category name gets cut short with only the first letter only displayed in the chart.
For example a category should read 'Run' but it only shows up as 'R'.
I also noted that this occurs in charts where there is only 1 category to display (so like a lone column chart with only one column displayed).
Would appreciate some help here :)
highchart() %>%
hc_title(text = "Creative Performance") %>%
hc_yAxis_multiples(
list(title = list(text = "Spend"),labels=list(format ='${value:,.2f}'), min=0, max=max(data_creative_trueview$Spend), showFirstLabel= TRUE,showLastLabel=TRUE,opposite = FALSE),
list(title = list(text = "TrueView: CPCV"),min=0,max = max(data_creative_trueview$`TrueView: CPCV`)+0.5, labels = list(format = "${value:,.2f}"),showLastLabel = FALSE, opposite = TRUE)) %>%
hc_add_series(data = data_creative_trueview, type= "column", hcaes(y=Spend), name="Spend") %>%
hc_add_series(data = data_creative_trueview, type = "line", hcaes(y=`TrueView: CPCV`), name="TrueView: CPCV", yAxis=1) %>%
hc_xAxis(title="Creative", categories=data_creative_trueview$Creative) %>%
hc_tooltip(pointFormat = '${point.y:,.2f}') %>%
emphasized text hc_legend(align = "right", verticalAlign = "top")
I found an answer right after I posted this. Apparently this is a common issue. Categories must be provided as a list when there is only one category. Refer to: https://github.com/jbkunst/highcharter/issues/173
In my case xlabel={{"64"}} showed only 6 where as xlabel={{"64",}} gave me 64 which was what I have wanted.

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).

Rcharts: plot only shows first character of label

I recently switched from ggplot to Rcharts and have a fairly simple question about the labels.
Sample data
data_1 <- data.table(Filter = c('Filter 1', 'Filter 2'),
Amount = c(100, 50))
data_2 <- data.table(Filter = c('Filter 1'),
Amount = c(100))
Plots
hPlot(Amount ~ Filter, data = data_1, type = 'bar', group.na = 'NA\'s')
hPlot(Amount ~ Filter, data = data_2, type = 'bar', group.na = 'NA\'s')
Question:
Why do we see the correct label in the first plot, but only the first letter of the label in the second plot? This issue always occurs when the number of rows = 1 (as it is in data_2).
Does anyone has a quick fix / workaround?

Shiny with plotly

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)

Resources