Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format dygraphs labels in R - comma separate thousands place?

I am working with the htmlwidget dygraphs for R. My series spans a range from about 0 to 150,000.

I have tried using dyOptions(labelsKMB = "K") -- this formats y-axis as 0K, 20K, 40K, ... - however, as a result, the legend is also formatted with rounded values - e.g. 22K, 42K, etc..

I'd like to know if the following are possible and how to accomplish them:

  1. Format the y-axis in thousands, but leave the legend as actual (non-rounded) values?
  2. Use a comma separated format for thousands on either (or both) the y-axis and the legend? That is, rather than display 10000 on the y-axis, it is formatted as 10,000 -- likewise, actual values in the legend such as 2523 are formatted as 2,523.

I am pushing this into an interactive RMarkdown document. Perhaps custom CSS is a way to do this?

like image 240
JasonAizkalns Avatar asked Feb 12 '15 19:02

JasonAizkalns


2 Answers

You can specify a specific javascript function to set the labels of x axis independently. As an example, here is how you can modify the y-axis of the dygraph demo:

library(dygraphs)
library(htmlwidgets)

nhtempBig<-nhtemp*500
nhtempBig

valueFormatter<-"function formatValue(v) {
var suffixes = ['', 'K', 'M', 'G', 'T'];
  if (v < 1000) return v;
  var magnitude = Math.ceil(String(Math.floor(v)).length / 3-1);
  if (magnitude > suffixes.length - 1)
    magnitude = suffixes.length - 1;
  return String(Math.round(v / Math.pow(10, magnitude * 3), 2)) +suffixes[magnitude]}"




 dygraph(nhtempBig, main = "New Haven Temperatures") %>%
  dyAxis("y", label = "Temp (F)", valueRange = c(0, 150000),axisLabelFormatter=JS(valueFormatter)) %>%
  dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = FALSE)

I just made up a dummy function to change the axis labels, the legend should stay the same.

Edit: added a formatting function, modified from one of the dygraph example

like image 108
NicE Avatar answered Nov 10 '22 07:11

NicE


Expanding on my comment above with a full example:

library(dygraphs)
library(htmlwidgets)
FUNC_JSFormatNumber <- "function(x) {return x.toString().replace(/(\\d)(?=(\\d{3})+(?!\\d))/g, '$1,')}"
dygraph(ldeaths) %>%
  dyAxis("y", axisLabelFormatter=JS(FUNC_JSFormatNumber), valueFormatter=JS(FUNC_JSFormatNumber))
like image 20
JasonAizkalns Avatar answered Nov 10 '22 08:11

JasonAizkalns