【问题标题】:Plotly R converts numeric factor levels to numeric values [duplicate]Plotly R将数字因子水平转换为数值[重复]
【发布时间】:2016-05-09 17:47:47
【问题描述】:

我有一个像这样的基本数据框,我正在尝试绘制 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')

【问题讨论】:

  • 作为替代方案,您可以使用 ggplotly()

标签: r ggplot2 plotly


【解决方案1】:

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

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

【讨论】:

  • 哦,我不知道那个选项。谢谢你。它解决了我的部分问题。现在,我的标签是 41234470 这样的 dna 突变位置,即使使用此选项,轴标签也会缩写为 41.2M,就好像它是一个数值一样。
  • 您可以使用plot_ly(df, x = x, y = y, mode = 'markers') %&gt;% layout(xaxis = list(type = "category")) 解决其他问题。 ggplotly() 通过将 xaxis 值强制为数字来处理因子,但添加与因子标签匹配的刻度标签。
猜你喜欢
  • 1970-01-01
  • 2014-12-03
  • 2017-07-18
  • 2015-07-19
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
相关资源
最近更新 更多