如何强制 plotly R 用类别轴绘制缺失值

How to force plotly R to plot missing values with category axis

我想在 plotly R 中绘制一个简单的条形图,默认情况下它将跳过 NA 观察。在 ggplot 中,我们有一个参数来禁用默认的 NA 删除,或者我们可以自定义轴限制。但是我无法巧妙地完成它。

dt_plot <- data.frame(categories = letters[1:10], values = c(rep(NA_integer_, 3), 1:5, rep(NA_integer_, 2)))
plot_ly(data = dt_plot) %>%
  add_bars(x = ~categories, y = ~values)

我想将 x 轴显示为一致的字母 1:10,因为我实际上将此图包含在具有动态数据选择的闪亮应用程序中。有些数据在所有 x 值中都有值,有些只在子集中有值。我想让情节保持一致并始终显示完整的 x 值。

,但答案不适用于我的情况,因为我使用的是类别类型 x 轴:

https://plot.ly/r/reference/#layout-xaxis

If the axis type is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

我尝试了不同的范围组合,但没有用。 plotly 似乎总是首先删除 NA 观察结果。

Carson Sievert 在 a related issue 中提出了一个黑客建议,但它对我来说也没有用。

# this do show all the x values but the plot is wrong
layout(xaxis = list(type = "category", tickvals = 1:10/10, ticktext = letters[1:10], range = c(0, 1)))

通过检查绘图对象,似乎在构建绘图之前删除了 NA 数据:

{
  "visdat": {
    "7abc7354f619": ["function () ", "plotlyVisDat"]
  },
  "cur_data": "7abc7354f619",
  "attrs": {
    "7abc7354f619": {
      "alpha_stroke": 1,
      "sizes": [10, 100],
      "spans": [1, 20],
      "x": {},
      "y": {},
      "type": "bar",
      "inherit": true
    }
  },
  "layout": {
    "margin": {
      "b": 40,
      "l": 60,
      "t": 25,
      "r": 10
    },
    "xaxis": {
      "domain": [0, 1],
      "automargin": true,
      "range": [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
      "title": "categories",
      "type": "category",
      "categoryorder": "array",
      "categoryarray": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
    },
    "yaxis": {
      "domain": [0, 1],
      "automargin": true,
      "title": "values"
    },
    "hovermode": "closest",
    "showlegend": false
  },
  "source": "A",
  "config": {
    "showSendToCloud": false
  },
  "data": [
    {
      "x": ["d", "e", "f", "g", "h"],
      "y": [1, 2, 3, 4, 5],
      "type": "bar",
      "marker": {
        "color": "rgba(31,119,180,1)",
        "line": {
          "color": "rgba(31,119,180,1)"
        }
      },
      "error_y": {
        "color": "rgba(31,119,180,1)"
      },
      "error_x": {
        "color": "rgba(31,119,180,1)"
      },
      "xaxis": "x",
      "yaxis": "y",
      "frame": null
    }
  ],
...

参考文献中有信息:https://plotly.com/r/reference/layout/xaxis/#layout-xaxis-range,但不是很明显。

但首先:分类变量需要 factor

其次,您需要指定从 0 到级别数 -1 的范围。为了更好看,在末端使用 +-0.5

dt_plot <- data.frame(categories = letters[1:10], values = c(rep(NA_integer_, 3), 1:5, rep(NA_integer_, 2)))
dt_plot$categories <- as.factor(dt_plot$categories)
plot_ly(data = dt_plot) %>%
  add_bars(x = ~categories, y = ~values)%>% 
  layout(xaxis = list(range = list(-0.5, 9.5)))