Plotly R将数字因子级别转换为数值

时间:2016-05-09 17:47:47

标签: r ggplot2 plotly

我有一个像这样的基本数据框,我试图在情节中绘制x对y。它出于某种原因将我的x值转换为数字(连续比例)和绘图,而不是将它们保留为因子。知道为什么它会这样做以及我能做些什么才能使它表现得不同(正确)?

df <- data.frame(x = c(1, 2, 4, 8, 16, 32), y = 1:6)
df$x <- as.factor(df$x)

str(df)
'data.frame':   6 obs. of  2 variables:
 $ x: Factor w/ 6 levels "1","2","4","8",..: 1 2 3 4 5 6
 $ y: int  1 2 3 4 5 6

levels(df$x)
[1] "1"  "2"  "4"  "8"  "16" "32"

使用ggplot进行绘图,这显然是正确的:

library(ggplot2)
ggplot(df, aes(x = x, y = y)) + geom_point()

使用plotly R绘图,将x视为连续值:

library(plotly)
plot_ly(df, x = x, y = y, mode = 'markers')

1 个答案:

答案 0 :(得分:0)

如果你只想让它像ggplot2一样工作,你可以在plotly中强制x变量来显示因子的标签:

library(plotly)
plot_ly(df, x = labels(x), y = y, mode = 'markers')

enter image description here