0

I want to use ggplot to create a line graph, with the values of each 'Molecule' represented by a different line. I want to use 'Family' to colour each line. I am having issues with this and can't seem to represent the individual values as separate lines, nor colour them based on their family.

df.long = melt(df, id.vars = c("Molecule", "Family"), measure.vars = c(3:7)) ggplot(df.long, aes(variable, value)) + geom_line(aes(colour = Molecule) 

I end up plotting something like this:

enter image description here

If someone could help me work this out, I would appreciate it.

This is how my data is organized, in wide format:

Molecule Family Pos1 Pos2 Pos3 Pos4 Pos5
A i 2.178 1.289 0.656 0.956 0.711
B ii 1.478 0.889 0.578 0.689 0.444
C ii 1.389 1.078 1.189 0.944 1.844

1 Answer 1

1

To get separate lines for each Molecule you have to map Molecule on the group aes:

library(ggplot2) library(reshape2) df <- read.table(text = "Molecule Family Pos1 Pos2 Pos3 Pos4 Pos5 A i 2.178 1.289 0.656 0.956 0.711 B ii 1.478 0.889 0.578 0.689 0.444 C ii 1.389 1.078 1.189 0.944 1.844", header = TRUE) df.long = melt(df, id.vars = c("Molecule", "Family"), measure.vars = c(3:7)) ggplot(df.long, aes(variable, value)) + geom_line(aes(colour = Family, group = Molecule)) 

Sign up to request clarification or add additional context in comments.

3 Comments

Holy cow! Thank you so much. What a great fix! Edit: Solved the problem
(: BTW: The reason why we need the group aes is that your x variable is itself a categorical variable. In that case ggplot2 by default uses the variable mapped on x for the grouping, that's why you get the vertical lines.
That makes a lot of sense. So many methods to learn! Much appreciated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.