我正在尝试使用 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")
返回:
但是,如果我筛选出仅包含数字的组,则效果很好:
dfc=subset(dfb,dfb$groups!='1')
plot_ly(dfc,
x = groups,
y = counts,
type = "bar")
为什么会这样? 以及如何解决这个问题?
我使用 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))
关于R plotly x 轴字符/因子(组合数字和 -)。绘图仅显示仅包含数字的轴。漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38565902/