R plotly x 轴字符/因子(组合数字和 -)。绘图仅显示仅包含数字的轴。漏洞?

标签 r plotly

我正在尝试使用 plotly 绘制一个以字符串(组合数)作为 x 轴的条形图。
(“1”、“2”、“3”、“4 - 5”、“6 - 8”、“9 - 13”、“14 - 21”、“22 - 34”、“35 - 55”)

但是,仅绘制了 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

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

我使用 plotly 是因为我想将它与 Shiny 一起使用,目前它最适合我。

我没有使用 ggplotly(制作 ggplot 然后将其转换为 plotly)因为有时轴标题会被切断。

最佳答案

恐怕这是一个重复的问题: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))

两者都生成图形 (虽然 x 轴标题不同) enter image description here

关于R plotly x 轴字符/因子(组合数字和 -)。绘图仅显示仅包含数字的轴。漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38565902/

相关文章:

r - 在直方图的 Y 轴上打断

r - DT 和 Shiny : Formatting numbers in a datatable with filters

r - R Shiny 中的复选框组输入与 Plotly

r - 我可以放大一个图并让其他图也以同样的方式缩放吗? (ggplot 和plotly)

python - 散点图同一点重复多次python

r - 在另一个表的同一行的多列上过滤 df?

R dplyr未完成滞后日期差计算

重置每个方面的颜色ggplot2 R

Python:Plotly 3D 曲面图

python - Jupyter notebook 不显示图形..(只是图形)