0

After looking at "ggplot2" the book, this site, the documentation, cookbook-r and R-Studio cheat sheet and endeavoring to get ggplot2 data structure information specific to faceting, there still seems to be a discontinuity. Running in Win10 with R3.3.1 and ggplot2 2.1.0

The data in question needs to be plotted for the latter three columns as Y and dim once as X suggesting facet_wrap.

>elbow
   dim       rss     pdrss     dpdrss  
1    2 1011.5940        NA         NA  
2    3  716.0400 41.276192         NA  
3    4  588.8822 21.593068 19.6831234
4    5  517.5983 13.772050  7.8210182
5    6  463.7904 11.601785  2.1702656
6    7  422.5073  9.770970  1.8308150
7    8  391.2289  7.994904  1.7760653
8    9  360.3259  8.576408 -0.5815033
9   10  335.5152  7.394817  1.1815904
10  11  315.8829  6.215040  1.1797778
11  12  296.1883  6.649362 -0.4343228
12  13  278.5907  6.316657  0.3327057

> str(elbow)
'data.frame':   12 obs. of  4 variables:
 $ dim   : int  2 3 4 5 6 7 8 9 10 11 ...
 $ rss   : num  1012 716 589 518 464 ...
 $ pdrss : num  NA 41.3 21.6 13.8 11.6 ...
 $ dpdrss: num  NA NA 19.68 7.82 2.17 ...

plots nicely with

> abreak = c(1,3,5,7,9,11,13)
> alabel = c("1","3","5","7","9","11","13")
> ggplot(elbow, aes(dim,rss))+geom_point() 
   +scale_x_continuous(breaks=abreak,labels=alabel)

but fails with

> ggplot(elbow, aes(dim, value)) + 
    geom_point() + 
    facet_wrap(~variable, scales = "free_y", ncol = 1)

it works with

> ggplot(economics_long, aes(date, value)) + geom_line() + 
    facet_wrap(~variable, scales = "free_y", ncol = 1)

The nature of str(economics_long) is quite different with the significance of the elements not clearly related to the plot. The data needs to talk but what say?

How may I learn how the economics_long data and the like for other plots structure produced, or parhaps how the information plotting needs can be provided in the call.

HGB
  • 1
  • 1
  • Sorry, but the language makes it impossible for me to understand your question. Apparently you have found out that ggplot2 expects data to be in "long format" which is explained in almost every ggplot2 tutorial. There are several tools for reshaping data. I still prefer the reshape2 package for reshaping data.frames. What exactly is your question? – Roland Oct 27 '16 at 11:24
  • You need a discrete or a factor variable in place of "value". As Roland says, reshape data. It would also be interesting that the problem was reproducible (sample data) and error messages you have (does not work "but fail with"). Welcome to SO. – PereG Oct 27 '16 at 11:33
  • `library(tidyr); elbow %>% gather(variable, value, -dim) %>% ggplot(aes(dim, value)) + geom_point() + facet_wrap(~variable, scales = "free_y", ncol = 1)` – Michael Griffiths Oct 27 '16 at 12:00
  • That did it most elegantly Michael, now I will decode what it is doing and put it in my toolkit. – HGB Nov 03 '16 at 00:43

0 Answers0