R - Creating Scatter Plot from Data Frame

user1192748 picture user1192748 · Feb 27, 2013 · Viewed 11.6k times · Source

i've got a data frame all that look like this:

http://pastebin.com/Xc1HEYyH

Now I want to create a scatter plot with the column headings in the x-axis and the respective values as the data points. For example:

7|                 x  
6|          x      x  
5|  x       x      x     x    
4|  x       x            x 
3|                             x      x  
2|                             x      x
1|
 ---------------------------------------
    STM    STM    STM   PIC   PIC    PIC
   cold   normal  hot  cold  normal  hot

This should be easy, but I can not figure out how.

Regards

Answer

Arun picture Arun · Feb 27, 2013

The basic idea, if you want to plot using Hadley's ggplot2 is to get your data of the form:

        x          y
col_names     values

And this can be done by using melt function from Hadley's reshape2. Do ?melt to see the possible arguments. However, here since we want to melt the whole data.frame, we just need,

melt(all) 
# this gives the data in format:
#   variable value
# 1 STM_cold   6.0
# 2 STM_cold   6.0
# 3 STM_cold   5.9
# 4 STM_cold   6.1
# 5 STM_cold   5.5
# 6 STM_cold   5.6

Here, x will be then column variable and y will be corresponding value column.

require(ggplot2)
require(reshape2)
ggplot(data = melt(all), aes(x=variable, y=value)) + 
             geom_point(aes(colour=variable))

If you don't want the colours, then just remove aes(colour=variable) inside geom_point so that it becomes geom_point().

enter image description here

Edit: I should probably mention here, that you could also replace geom_point with geom_jitter that'll give you, well, jittered points:

enter image description here