Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

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

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.

enter image description here

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...