Reputation: 2529
Say I have the following data:
require(reshape2)
require(ggplot2)
data <- data.frame(id=seq(1,5,1), var1=c(10,3,5,7,8), label1=c(2,2,2,3,2), var2=c(12, 6, 6, 8, 6), label2=c(7,7,6,7,5))
I use melt
to reshape the data to prepare it for ggplot
.
data_graph <- melt(data[,c(1,2,4)], id="id")
I then plot it, with the values labeling each point:
ggplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=value), size=5, hjust=-.6, vjust=1.5)
However, I actually want the label1
vector labeling the line corresponding to var1
and analogously for label2
and var2
. How would I do this?
Upvotes: 1
Views: 1094
Reputation: 7119
I think to solve your problem you need to prepare a different data.frame for ggplot2, one wiht id, variable, label and value.
# dataset for var1
df1 <- cbind(data[,c(1,3,2)], 'var1')
colnames(df1) <- c('id', 'label', 'value', 'variable')
# dataset for var2
df2 <- cbind(data[,c(1,5,4)], 'var2')
colnames(df2) <- c('id', 'label', 'value', 'variable')
# putting them together
data_graph <- rbind(df1,df2)
Now your graph can be generated in this way:
gplot(data=data_graph, aes(y=value, x=id, group=variable, col=variable)) +
geom_line(size=2) + geom_point() +
geom_text(aes(label=label), size=5, hjust=-.6, vjust=1.5)
And this is the result, with the values from the label columns as labels for your data points:
Upvotes: 2