R图表x轴字符/因子(组合编号和 - )。绘图仅显示仅包含数字的轴。错误?

时间:2016-07-25 10:56:19

标签: r plotly

我正在尝试使用plotly绘制带有字符串(组合编号)作为x轴的条形图。
(“1”,“2”,“3”,“4 - 5”,“6 - 8”,“9 - 13”,“14 - 21”,“22 - 34”,“35 - 55”)< / p>

但是,仅绘制了3个数据。 (“1”,“2”,“3”)

以下是代码:

library(plotly)

dfb = structure(groups = c("1", "2", "3", "4 - 5", "6 - 8",
                        "9 - 13", "14 - 21", "22 - 34", "35 - 55"),
    counts = c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15)),
  class = c("data.frame"),
  row.names = c(NA,-9L),
  .Names = c("groups","counts")
)

  plot_ly(dfb,
      x = groups,
      y = counts,
      type = "bar")

返回:

enter image description here

但是,如果我过滤了仅包含数字的组,那么它运作良好:

  dfc=subset(dfb,dfb$groups!='1')
  plot_ly(dfc,
      x = groups,
      y = counts,
      type = "bar")

enter image description here

为什么会这样? 以及如何解决这个问题?

我正在使用情节,因为我想用Shiny来使用它,现在它最适合我。

我没有使用ggplotly(make ggplot然后将其转换为plotly),因为有时候轴被切断了。

1 个答案:

答案 0 :(得分:1)

我担心这是一个重复的问题:Plotly R: Cant get points to plot when two values present per x factor level。但是,您有几个解决方案:

解决方案1 ​​ (也在提及的问题中提出)

library(plotly)

dfb = data.frame(groups= c("1", "2", "3", "4 - 5", "6 - 8","9 - 13", "14 - 21", "22 - 34", "35 - 55"),
            counts=c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15))

plot_ly(dfb,
   x = groups,
   y = counts,
   type = "bar") %>%
   layout(xaxis=list(type='category'))

解决方案2 (不太优雅)

groups_str <- c("1", "2", "3", "4 - 5", "6 - 8","9 - 13", "14 - 21", "22 - 34", "35 - 55")
groups <- 1:length(groups_str)

dfb = data.frame(groups= groups,
            counts=c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15))

plot_ly(dfb,
   x = groups,
   y = counts,
   type = "bar") %>%
   layout(xaxis=list(tickmode='array', tickvals=groups, ticktext=groups_str))

两者都产生了数字 (虽然具有不同的xaxis标题) enter image description here