【问题标题】:How to align a bar and a line chart in ggvis in a dual y-axes plot?如何在双 y 轴图中对齐 ggvis 中的条形图和折线图?
【发布时间】:2014-10-13 09:34:35
【问题描述】:

使用以下代码:

library(ggvis)
library(dplyr)
mydf2 <- iris %>%
  group_by(Species) %>%
  summarize(Sepal.Length = mean(Sepal.Length),
            Sepal.Width = mean(Sepal.Width)) 

mydf2 %>% as.data.frame()  %>% 
  ggvis(x = ~ Species, y = ~ Sepal.Length ) %>%
  layer_bars(fillOpacity := 0.1 ) %>%
  add_axis("y", "ywidth", orient = "right", grid = FALSE) %>%
  layer_lines(prop("y", ~ Sepal.Width, scale = "ywidth")) %>%
  add_axis('x', title='the species', properties = axis_props(labels=list(fill='blank'))) %>%
  add_axis('x', 'myx2', orient='bottom', title='') %>%
  layer_lines(prop("x", ~ Species, scale = "myx2"), stroke := 'blank')

输出:

我的问题是:

  • 有人知道在这个双 y 轴图上对齐条形图和折线图的方法吗?我希望两个图表的刻度线在 x 轴上对齐。

编辑

我决定编辑这个问题并提供一个更好的例子来更好地说明问题。

【问题讨论】:

  • 这个例子不适合我。 Error: Unknown properties: size..
  • 很抱歉。我现在修好了。

标签: r bar-chart linechart ggvis multiple-axes


【解决方案1】:

经过大约 4 个月的研究和一些研究,我找到了解决这个问题的方法,尽管它有点像 hack:

mydf2 %>% as.data.frame() %>% mutate(Species2= as.numeric(Species)) %>% 
  ggvis(x = ~ Species2, y = ~ Sepal.Length ) %>%
  layer_bars(fillOpacity := 0.1, width = 0.9 ) %>%
  add_axis("y", "ywidth", orient = "right", grid = FALSE) %>%
  layer_lines(prop("y", ~ Sepal.Width, scale = "ywidth")) %>%
  add_axis('x', title='the species', properties = axis_props(labels=list(fill='blank'))) %>%
  add_axis('x', 'myx2', orient='bottom', title='', grid=F) %>%
  layer_lines(prop("x", ~ Species, scale = "myx2"), stroke := 'blank') 

输出

上述答案背后的原因是,为了使折线图和条形图对齐,x 轴需要是数字。因此,我制作了一个新的分类 x 轴,用于绘制一条不可见的线(检查最后两行代码)。结果不是最佳的,但它有效。

你也可以查看this的答案。

附:该问题的示例代码来自this github 上的帖子。上面已经(幸运地)作为一个问题在那里提出。如果它得到修复(或者有办法解决这个问题)我会更新答案。

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多