1

I am trying to create a plot with a line for each sample which has 24 measured values (i.e. data to be plotted are in rows rather than columns). An example of my data looks like this:

structure(c("23.96000", "25.92000", "20.13000", "20.39000", "13.88000", 
            "14.97000", "11.56000", "12.75000", " 8.86000", "10.33000", " 8.96000", 
            " 9.87000", " 7.540000", " 8.160000", " 6.670000", " 7.430000", 
            " 7.060000", " 7.040000", " 6.250000", " 7.200000", " 6.400000", 
            " 6.380000", " 6.70000", " 6.05000", " 5.590000", " 6.310000", 
            " 6.000000", " 5.770000"), .Dim = c(2L, 14L), .Dimnames = list(
              NULL, c("La", "Ce", "Pr", "Nd", "Sm", "Eu", "Gd", "Tb", "Dy", 
                      "Ho", "Er", "Tm", "Yb", "Lu")))

I have succeeded in creating the plot I want in matplot with the following code:

m <- as.matrix(data)
REE <- c('La','Ce','Pr','Nd','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu')

m2 <- m[,11:24]

#Plotting with matplot

matplot(t(m2), type = "l", log="y", xaxt ="n",ylab="C/C_Chondrite",ylim=c(1,100))
axis(1, at=1:length(REE), labels=REE)

Which generates: [REE plot][1]

I have tried the method described in this example: ggplot equivalent for matplot with only using geom_point() just to test out the function, however I am currently getting a plot like this:

[bad plot][1]

Is anyone able to help?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
lmm
  • 33
  • 1
  • 5
  • Hi & welcome to Stack Overflow! Please provide your `data` with`dput(data)` to make a [MCVE](https://stackoverflow.com/help/mcve). Thanks! – jay.sf Nov 21 '18 at 18:20
  • `ggplot` is powerful when you feed it long data, but unwieldy with wide data. I suggest you add a step before ggplot where you convert it, e.g. `tidyr::gather(element, value, La:Lu)`... – Jon Spring Nov 21 '18 at 19:16
  • 1
    Hi @jay.sf I have changed this - thanks for the tip! – lmm Nov 21 '18 at 21:11
  • @jay.sf I just saw it - thank you! – lmm Nov 22 '18 at 14:33

1 Answers1

0

You probably need to transpose your data, which is different in your example compared to the linked example.

data <- as.data.frame(t(data))  # transpose your data here with `t()`
data$id <- 1:nrow(data) 
library(reshape2)
plot_data <- melt(data,id.var="id")
library(ggplot2)
ggplot(plot_data, aes(x=id, y=value, group=variable, colour=variable)) +
  geom_point() +
  geom_line(aes(lty=variable))

Yields enter image description here

jay.sf
  • 60,139
  • 8
  • 53
  • 110