本文介绍了Plotly R将数字因子级别转换为数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的基本数据框,并且我试图以绘图方式绘制x与y的关系.由于某种原因,它会将我的x值转换为数字(连续比例)并绘制,而不是将其保留为因子.知道为什么会那样做以及我能做些什么来使其表现不同(正确)吗?

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"

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

Plotting with ggplot, which obviously does the right thing:

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

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

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

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

推荐答案

如果只想使其像ggplot2一样工作,则可以强制将x变量强制显示为因子的标签:

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

这篇关于Plotly R将数字因子级别转换为数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:25