i trying create line plot 2 stocks aapl , fb. instead of adding separate legend, print stock symbols along with lines. how can add geom_text following code?
i appreciate provide.
library (ggplot2) library(quantmod) getsymbols('aapl') getsymbols('fb') aapl = data.frame(aapl) fb = data.frame(fb) p1 = ggplot(aapl)+geom_line(data=aapl,aes(as.date(rownames(aapl)),aapl.adjusted,color="aapl")) p2 = p1+geom_line(data=fb,aes(as.date(rownames(fb)),fb.adjusted,color="fb")) p2 + xlab("year")+ylab("price")+theme_bw()+theme(legend.position="none")
this sort of plot perfect directlabels
package. , easier plot if data available in 1 dataframe.
# data library(quantmod) getsymbols('aapl') getsymbols('fb') aapl = data.frame(aapl) fb = data.frame(fb) # rbind 1 dataframe aapl$label = "aapl" fb$label = "fb" names = gsub("^fb\\.(.*$)", "\\1", names(fb)) names(aapl) = names names(fb) = names df = rbind(aapl, fb) # packages library(ggplot2) library(directlabels) # plot - labels @ beginning , ends of lines. ggplot(df, aes(as.date(rownames(df)), adjusted, group = label, colour = label)) + geom_line() + scale_colour_discrete(guide = 'none') + geom_dl(aes(label = label), method = list(dl.combine("first.points", "last.points")))
a better plot: increase space between end points of lines , labels. see here other options.
ggplot(df, aes(as.date(rownames(df)), adjusted, group = label, colour = label)) + geom_line() + scale_colour_discrete(guide = 'none') + scale_x_date(expand=c(0.1, 0)) + geom_dl(aes(label = label), method = list(dl.trans(x = x + .2), "last.points")) + geom_dl(aes(label = label), method = list(dl.trans(x = x - .2), "first.points"))
question possibly duplicate of this one.