简体   繁体   中英

How to plot the median and interquartile range of data that is already sorted by row in R?

My data frame is arrange the following way

time run1 run2 run3 run4 run5
0    2.0  3.0  3.5  4.0  2.0
1    1.5  2.5  4.5  6.5  2.5
2    [...]
[...]

I want to plot the median of the run values at each point in time. I tried to use stat_summary in ggplot but I dont know how to define the input for several y's(run1,run2,run3...) per x(timestep). And I am also not sure how to reformat the data best to avoid using it by row.

//Edit: Thanks for the help

library(reshape)
plotsmelt = melt(plots, id="time")

library(ggplot2)
ggplot(plotsmelt,aes(x=time,y=value)) + 
stat_summary(fun.data=median_hilow)

This code did the first part. Now my graph looks like this: (current graph) Can I reshape it to a smoothed/fitted line with interquartiles only at certain intervals like this: (desired format)

//Edit2: Thanks again! now I have the interquartiles at the right intervals. Now I only need a way to show a fitted/smoothed curve through the median datapoints and my graph is done.

Edit3: Case solved by user127649. thanks I actually sat some hours on trying to figure this out searching google before you helped me!

If you want to plot median and IQR, it sounds like you're trying to do a boxplot?

First you should rearrange your data

library(reshape)
data.m <- melt(data)

Then to plot it in ggplot

ggplot(data.m, aes(variable, value)
    geom_boxplot()

Edit #1

This might be a bit rough but something along these lines should get the IQR at desired intervals. I think you need to add the medians and IQR in separate layers:

ggplot(data.m,aes(x = time, y = value)) +
     stat_summary(fun.y = "median", geom = "point") +
     stat_summary(data = data.m[data.m$time %% 10 == 0, ], colour = fun.data = median_hilow)

Obviously, you should change data.m[data.m$time %% 10 == 0, ] to the interval you require

Edit #2

To add a fitted line:

 + geom_smooth(method = lm)

see ?geom_smooth for further options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM