添加文本到ggplot中的geom_line [英] Add text to geom_line in ggplot
本文介绍了添加文本到ggplot中的geom_line的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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。这是一种类似于我们的网站的网站,这是一种对于 directlabels
包来说,这个图是完美的。
#Data
library(quantmod)
getSymbols('AAPL')
getSymbols('FB')
AAPL = data.frame(AAPL)
FB = data.frame(FB)
#绑定到一个数据框
AAPL $ label =AAPL
FB $ label =FB
names = gsub(^ FB\\。(。* $) ,\\1,名称(FB))
名称(AAPL)=名称
名称(FB)=名称
df = rbind(AAPL,FB)
#包
库(ggplot2)
库(直接标签)
#在开始和结束行的标签。
ggplot(df,aes(as.Date(rownames(df)),Adjusted,group = label,color = label))+
geom_line()+
scale_colour_discrete(guide ='none ')+
geom_dl(aes(label = label),method = list(dl.combine(first.points,last.points)))
更好的情节:增加线条和标签端点之间的距离。其他选项请参阅
问题可能是这一个。
I am trying to create a line plot for 2 stocks AAPL and FB. Instead of adding a separate legend, I would like to print the stock symbols along with the lines. How can I add geom_text to the following code?
I appreciate any help you could 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 is the sort of plot that is perfect for the directlabels
package. And it is easier to plot if the data is available in one dataframe.
# Data
library(quantmod)
getSymbols('AAPL')
getSymbols('FB')
AAPL = data.frame(AAPL)
FB = data.frame(FB)
# rbind into one 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)
# The plot - labels at the beginning and the ends of the 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 the space between the end points of the lines and the labels. See here for 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 is possibly a duplicate of this one.
这篇关于添加文本到ggplot中的geom_line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文