Reputation: 8494
For a sample dataframe:
df <-structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"),
RSL = c(-1.84, 7.68, 18.4, 13, 39.8, 98.4, 129.9, 94.9, 138,
142, 10, 50, 60, 80), Age = c(1181.5, 4633, 5075.5, 5741.5,
8430.5, 9784, 10095, 10366, 10095, 10095, 6000, 13500, 13000,
12000)), .Names = c("Type", "RSL", "Age"), class = "data.frame", row.names = c(NA,
-14L))
I want to produce a graph with Age plotted against RSL (this is a single graph which forms part of many faceted graphs).
library(ggplot2)
library("reshape2")
g <- ggplot (df, aes(x=Age, y=RSL, shape = Type, colour=Type)) +
geom_point(size=1.5) +
scale_shape_manual(values=c(19,19,19,19,19))+ # sets shape of points
scale_colour_manual(values=c("red", "black", "blue")) #sets colour of points
g
But instead of A, B and C all being points, I want C to be a straight line (no points).
How is the best way to deal with this? I believe I need to melt my data:
df_long <- melt(df, id="Type")
... but can't work out how to assemble my graph?
Upvotes: 1
Views: 85
Reputation: 28379
Pass data with C
to a different geom
layer (in your case geom_line
) with data = subset(df, Type == "C"
.
library(ggplot2)
ggplot(subset(df, Type != "C"), aes(Age, RSL)) +
geom_point(aes(shape = Type, colour = Type), size = 1.5) +
geom_line(data = subset(df, Type == "C"), color = "blue") +
scale_shape_manual(values=c(19,19,19,19,19))+
scale_colour_manual(values = c("red", "black"))
Upvotes: 2
Reputation: 19756
This should also work and the legend will display all 3 too:
ggplot () +
geom_point(data = df, aes(x=Age, y=RSL, colour=Type), size=0, alpha = 0)+
geom_point(data = df[df$Type!="C",], aes(x=Age, y=RSL, colour = Type), size=1.5) +
geom_line(data = df[df$Type=="C",], aes(x=Age, y=RSL), size=0.7, color="blue")+
scale_colour_manual(values=c("red", "black", "blue"))
Upvotes: 3