How do I get discrete factor levels to be treated as continuous?

狂风中的少年 提交于 2019-11-27 03:25:03

问题


I have a data frame with columns initially labeled arbitrarily. Later on, I want to change these levels to numerical values. The following script illustrates the problem.

library(ggplot2)
library(reshape2)

m <- 10
n <- 6

nam <- list(c(),letters[1:n])
var <- as.data.frame(matrix(sort(rnorm(m*n)),m,n,F,nam))
dtf <- data.frame(t=seq(m)*0.1, var)
mdf <- melt(dtf, id=c('t'))

xs <- c(0.25,0.5,1.0,2.0,4.0,8.0)
levels(mdf$variable) <- xs

g <- ggplot(mdf,aes(variable,value,group=variable,colour=t))
g +
    geom_point() +
    #scale_x_continuous() +
    opts()

This plot is produced.

The 'variable' quantities are evenly spaced on the plot, even though numerically this is not true. How can I get the spacing on the x-axis correct?


回答1:


I think you can do this simply by transforming the variable to numeric:

mdf$variable <- as.numeric(as.character(mdf$variable))

g <- ggplot(mdf,aes(variable,value,group=variable,colour=t))
g +
    geom_point() +
    #scale_x_continuous() +
    opts()



回答2:


You need to convert your factor into numeric:

mdf$numVariable <- as.numeric(as.character(mdf$variable))

g <- ggplot(mdf,aes(numVariable,value,group=variable,colour=t))
g +
    geom_point() +
    #scale_x_continuous() +
    opts()

Or just do the conversion in the call to ggplot:

g <- ggplot(mdf,aes(as.numeric(as.character(variable)),value,group=variable,colour=t))


来源:https://stackoverflow.com/questions/6386314/how-do-i-get-discrete-factor-levels-to-be-treated-as-continuous

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