首页 > 解决方案 > 如何强制 plotly R 用类别轴绘制缺失值

问题描述

我想在 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

如果轴type是“类别”,它应该是数字,使用比例尺,每个类别按照出现的顺序从零开始分配一个序列号。

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

Carson Sievert 提出了一个相关的问题,但它也没有真正起作用。

# 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
    }
  ],
...

标签: r-plotly

解决方案


参考中有信息: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)))

推荐阅读