gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:33:02 24 4
gpt4 key购买 nike

我想在 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,因为我实际上将此图包含在具有动态数据选择的 Shiny 应用程序中。有些数据在所有 x 值中都有值,有些数据只在一个子集中有值。我想让绘图保持一致并始终显示完整的 x 值。

a similar question here ,但答案不适用于我的情况,因为我使用的是类别类型 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.



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

a related issue Carson Sievert 建议进行 hack 的地方,但它也没有真正对我有用。

# 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)))

关于r-plotly - 如何强制绘图 R 用类别轴绘制缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com