Plotly R converts numeric factor levels to numeric values [duplicate]

可紊 提交于 2020-01-07 00:48:27

问题


I have a basic data frame like this, and I am trying to plot x vs. y in plotly. It for some reason converts my x values to numeric (continuous scale) and plots instead of keeping them as factors. Any idea why it would do that and what I can do to make it behave differently (correctly)?

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"

Plotting with ggplot, which obviously does the right thing:

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

Plotting with plotly R, which treats x as a continuous value:

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

回答1:


If you only want to make it work as ggplot2 would, you can force the x variable in plotly to display the factor's labels:

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



来源:https://stackoverflow.com/questions/37122216/plotly-r-converts-numeric-factor-levels-to-numeric-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!