R交互式图形 - 删除因子级别\元素并使轴适应

时间:2017-03-16 11:35:30

标签: r plot ggplot2 interactive

我希望能够在R中呈现交互式图形,其呈现线条/条形/按特定因子分组的任何度量,并且能够产生一个或多个因子的级别(组)消失并让x和y轴适应这一点,对这种选择做出反应。

示例:

df <- data.frame(factor1 = c(rep("a", 3), rep("b", 3), rep("c", 3)),
             xAxisVar = c(1:7, 5, 9),
             yAxisVar = c(1:7, 5, 25))

ggplot(df, aes(xAxisVar, yAxisVar, group = factor1, color = factor1)) +
  geom_line() +
  geom_point()

enter image description here

在此图中,y轴延伸到25,因为1&#34;大&#34;因子水平观察&#34; c&#34;。我希望能够按下&#34; c&#34;或者将其过滤掉并让y轴对此作出响应,重新渲染图形达到6左右。

我已尝试过plotly ggplotly,您可以自动制作小组&#34; c&#34;消失,但没有重新渲染的情节来解释。建议?

1 个答案:

答案 0 :(得分:2)

您提到了ggplotly,因此如果您对plotly开放,可以尝试:

library(plotly)
library(reshape2)

#from long to wide
df_wide <- dcast(df, xAxisVar ~ factor1, value.var="yAxisVar")

plot_ly(df_wide, x = ~xAxisVar, y = ~a, name='a', type='scatter', mode='lines+markers')  %>%
  add_trace(y = ~b, name = 'b', type='scatter', mode='lines+markers') %>%
  add_trace(y = ~c, name = 'c', type='scatter', mode='lines+markers', connectgaps = TRUE) %>%
layout(
  updatemenus = list(
    list(
      type = "buttons",
      x = -0.1,
      y = 0.7,
      label = 'Category',
      buttons = list(
        list(method = "restyle",
             args = list('visible', c(TRUE, FALSE, FALSE)),
             label = "a"),
        list(method = "restyle",
             args = list('visible', c(FALSE, TRUE, FALSE)),
             label = "b"),
        list(method = "restyle",
             args = list('visible', c(FALSE, FALSE, TRUE)),
             label = "c")
      )
    )))