mrjoh3 / c3

c3 HTMLWidget Ploting
39 stars 51 forks source link

Mapping series to secondary y-axis #7

Closed hendrikvanb closed 6 years ago

hendrikvanb commented 6 years ago

I'm trying to create a chart where one series (a) is mapped to the primary y-axis as a line chart and another series on a different scale (b) is mapped to the secondary y-axis as an area chart. There is an exampl e that illustrates this kind of dual y-axis mapping in c3.js, but am am not sure how to translate this example for use with the c3 package in R. I've been able to implement something like this with ggplot2 using the following MWE:

library(tidyverse)

# generate MWE data
data <- data.frame(a = abs(runif(20)),
                  date = seq(as.Date(Sys.Date()), by = "day", length.out = 20)) %>% 
  mutate(b = rev(a)*100)

# working ggplot2 implementation
data %>% 
  ggplot(aes(x = date)) +
  geom_area(aes(y = b / 100), alpha = 0.2) +
  geom_line(aes(y = a)) +
  scale_y_continuous(name = 'a', sec.axis = sec_axis(~ . * 100, name = 'b'), limits = c(0, 1))

However, I'm struggling to recreate something similar using c3:

library(c3)
# non-working c3 attempt 
data %>% 
  c3(x = 'date', y = 'a', y2 = 'b') %>% 
  c3_mixedGeom(types = list(a = 'line', b = 'area')) %>% 
  grid('y', show =  T) %>% 
  xAxis(type = 'timeseries', tick = list(format = "%Y-%m-%d")) %>% 
  yAxis(min = 0, label = list(text = 'a')) %>% 
  y2Axis(show = T, label = list(text = 'b')) 

Is this currently possible with c3? If so, where am I going wrong? Thanks!

mrjoh3 commented 6 years ago

It is possible, you just need to allocate the axes via the c3 data object. Unfortunately, I have not done a good job of documenting this.

Please try the following:

data %>% c3(x = 'date',
            axes = list(a = 'y',
                        b = 'y2')) %>% 
  c3_mixedGeom(types = list(a='line',
                                b='area')) %>% 
y2Axis()

Note the axes = argument. This is where the work is done, y2Axis() simply makes the second axis visible.

hendrikvanb commented 6 years ago

Thank you, Matt! This works a treat and also nicely illustrates how to specify other data attributes. Your help (and the excellent package) is much appreciated.

mrjoh3 commented 6 years ago

you are most welcome. closed with commit 706bf33