Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting multiple smooth lines from a dataframe

Tags:

graph

plot

r

I am relatively new to R. I am trying to plot a dataframe loaded from a csv file. The data consists of 6 columns like this:

xval,col1,col2,col3,col4,col5

The first column (xval) consist of a sequence of monotonically increasing positive integers (e.g. 10, 40, 60 etc), the other columns columns 1 to 5, consist of floating point numbers.

I want to create a plot in R as follows:

  • plot xval term on x axis
  • plot remaining columns (col1 ... col5) lines
  • create a legend legend with col2, ... col5 renamed

The data to be plotted (col1, ... col5) are 'snapshot' values so although I want to plot them as lines, I want the lines to be smoothed (i.e. interpolated).

I am looking for a snippet that help me create the plot once I have read the data into a dataframe. Any help will be appreciated.

like image 514
Homunculus Reticulli Avatar asked Dec 21 '22 20:12

Homunculus Reticulli


1 Answers

Have a look at ggplot2

#create dummy data
n <- 200
dataset <- data.frame(xval = runif(n), col1 = rnorm(n), col2 = rnorm(n, sd = 2), col3 = rnorm(n, mean = seq(0, 2, length = n)), col4 = rnorm(n, sd = seq(0, 1, length = n)), col5 = rnorm(n, mean = 1))
#convert data to long format
library(reshape)
Molten <- melt(dataset, id.vars = "xval")
#plot it
library(ggplot2)
ggplot(Molten, aes(x = xval, y = value, colour = variable)) + 
    geom_smooth() + geom_point()
#some tweaking
ggplot(Molten, aes(x = xval, y = value, colour = variable)) + 
    geom_smooth(se = FALSE) + geom_point() + theme_bw() + 
    scale_x_continuous("the x label") + scale_x_continuous("the y label") +
    scale_colour_discrete("")

enter image description here

like image 156
Thierry Avatar answered Jan 29 '23 03:01

Thierry