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
349 views
in Technique[技术] by (71.8m points)

r - ggplot2 one line per each row dataframe

I have a CSV file that contains the following data:

user,Measurement1,Measurement2,Measurement3,group
1,0.1,0.7,0.2,3
2,0.3,0.3,0.4,2
3,0.3,0.3,0.4,2

I need to plot one line per each user. The x axis can be just 1,2,3 (one point per each measurement labeled as before,at,after, but I can work out the labeling later). The color will be set by the group columns I found a plot similar to the one I need but I don't want to use the user code as the x value.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

ggplot likes data in the 'long' format: i.e., a column for every dimension, and a row for every observation. Your data is currently 'wide'. Use the reshape package to go from one to the other.

Do I understand correctly that you want Measurement1, Measurement2, and Measurement3 to be on the x-axis? (So that, in your data, user 1's line would go from 0.1 to 0.7 to 0.2? If so, you want something like this:

require(reshape)

#Recreate your data frame
user <- gl(3, 1)
Meas1 <- c(0.7, 0.3, 0.3)
Meas2 <- c(0.7, 0.3, 0.3)
Meas3 <- c(0.2, 0.4, 0.4)
group <- c(3, 2, 2)
df <- data.frame(user=user, Meas1=Meas1, Meas2=Meas2, Meas3=Meas3, group=group)

#'melt' the data frame into long format
dfm <- melt(df, id.vars=c("user", "group"))

ggplot(dfm, aes(x=as.numeric(variable), y=value, colour=user)) + geom_line()

enter image description here


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

...