ranell
ranell

Reputation: 703

Plot a Matrix with ggplot

I want to display this matrix with ggplot in order to have lines : Example : in X the portion from 1 to 12, and in Y ther is 5 lines (categories) with different colors, and their corresponding values. Example first point x=1 and Y = 12.25 in red Second point x=2 and Y=0.9423 in green

  DF <- read.table(text = "
                Portion         1         2        3         4         5
    1                 1 12.250000 0.9423077 33.92308 0.0000000 1.8846154
    2                 2  6.236364 1.7818182 38.30909 0.8909091 1.7818182
    3                 3  9.333333 1.8666667 28.00000 0.0000000 2.8000000
    4                 4  9.454545 2.8363636 34.03636 4.7272727 0.9454545
    5                 5 27.818182 0.0000000 19.47273 2.7818182 0.9272727
    6                 6 19.771930 2.5789474 19.77193 0.8596491 6.0175439
    7                 7 22.350877 1.7192982 22.35088 0.8596491 1.7192982
    8                 8 17.769231 4.0384615 15.34615 0.8076923 4.0384615
    9                 9 16.925373 8.8656716 23.37313 2.4179104 2.4179104
    10               10 10.036364 8.3636364 25.09091 0.8363636 1.6727273
    11               11  8.937500 8.9375000  8.12500 0.0000000 0.0000000
    12               12 12.157895 5.2105263 14.76316 0.8684211 0.0000000", header = TRUE)
      newResults <- as.data.frame(DF)

    library(reshape2) 
    R = data.frame(Portion = c('1','2','3','4','5','6','7','8','9','10','11','12'), newResults[,1], newResults[,2], newResults[,3], newResults[,4], newResults[,5])
    meltR = melt(R, id = "Portion")
    ggplot(meltR, aes(reorder(Portion, -value), y = value, group = variable, colour = variable)) +   geom_line().

Why is my X value are not ordered ? and is it the healthiest way to do this ?

Thanks a lot.

Upvotes: 1

Views: 9559

Answers (1)

coffeinjunky
coffeinjunky

Reputation: 11514

Try:

meltR = melt(DF, id = "Portion")
ggplot(meltR, aes(x=Portion, y = value, group = variable, colour = variable)) +   geom_line()

In this case there is no need to reorder anything in the aesthetic for ggplot. This will give you the following graph:

enter image description here

You may want to change the names of the variables, either by renaming them in the first step, or by providing custom labels to ggplot.

Upvotes: 5

Related Questions