Plotly R converts numeric factor levels to numeric

2019-09-10 12:49发布

问题:

This question already has an answer here:

  • Plotly R: Cant get points to plot when two values present per x factor level 1 answer

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



标签: r ggplot2 plotly