2016-06-06 3 views
3

2 개의 주식 AAPL 및 FB에 대한 선 그림을 만들려고합니다. 대신 별도의 범례을 추가하면 을 따라 주식 기호를과 함께 인쇄하고 싶습니다. geom_text를 다음 코드에 어떻게 추가 할 수 있습니까?
제공 할 수있는 도움에 감사드립니다. (가) label은 표시 할,ggplot의 geom_line에 텍스트 추가

x, y 위치를 정의 (그리고 color) :

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") 

답변

2

당신은 단순히 유 말했듯이 geom_text을 추가해야

enter image description here

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") +  
geom_text(aes(x = as.Date("2011-06-07"), y = 60, label = "AAPL", color = "AAPL")) + 
geom_text(aes(x = as.Date("2014-10-01"), y = 45, label = "FB", color = "FB")) 

수정

xy의 위치를 ​​geom_text에 자동으로 찾으려면 변수 개수를 늘리면 레이블이 겹치는 새로운 문제가 발생합니다. 다음은 x와`Y

AAPL$date = rownames(AAPL) 
AAPL$var1 = "AAPL" 
names(AAPL)[grep("AAPL", names(AAPL))] = gsub("AAPL.", "", names(AAPL)[grep("AAPL", names(AAPL))]) 
FB$date = rownames(FB) 
FB$var1 = "FB" 
names(FB)[grep("FB", names(FB))] = gsub("FB.", "", names(FB)[grep("FB", names(FB))]) 

# bind the 2 data frames 
df = rbind(AAPL, FB) 

# where do you want the legend to appear 
legend = data.frame(matrix(ncol = 3, nrow = length(unique(df$var1)))) 
colnames(legend) = c("x_pos" , "y_pos" , "label") 
legend$label = unique(df$var1) 
legend$x_pos = as.POSIXct(legend$x_pos) 

df$date = as.POSIXct(df$date) 
for (i in legend$label) 
{ 
    legend$x_pos[legend$label == i] <- as.POSIXct(min(df$date[df$var1 == i]) + 
as.numeric(difftime(max(df$date[df$var1 == i]), min(df$date[df$var1 == i]), units = "sec"))/2) 
    legend$y_pos[legend$label == i] <- df$Adjusted[df$date > legend$x_pos[legend$label == i] & df$var1 == i][1] 
} 

# Plot 
ggplot(df, aes(x = as.POSIXct(date), y = Adjusted, color = var1)) + 
geom_line() + xlab("Year") + ylab("Price") + 
geom_text(data = legend, aes(x = x_pos, y = y_pos, label = label, color = label, hjust = -1, vjust = 1)) 
+ guides(color = F) 

enter image description here

+0

bVa 제안 해 주셔서 감사합니다. 효과가있을 것입니다. 그러나 x, y 좌표를 지정하지 않고 선으로 텍스트를 인쇄하는 방법을 찾고 있습니다. 주식을 더 추가하거나 더 많은 차트를 생성하면 좌표를 찾고/추가하는 것이 약간 번거로워집니다. – user6296218

+0

새로운 문제가 생길 것입니다 : 겹쳐지는 텍스트. 편집 된 답변을 참조하십시오. – bVa

+0

다른 솔루션을 제안 해 주셔서 감사합니다. 귀하가 진술 한 바와 같이, 솔루션이 더 복잡해질 것이라는 데 동의합니다. 나는 그것을 간단하게하고 싶다. 도와 주셔서 감사합니다. – user6296218

6

이것은 directlabels 패키지에 대한 완벽한 플롯의 일종을 정의하는 방법을 적용 할 수, 솔루션의 시작입니다. 또한 데이터가 하나의 데이터 프레임에서 사용 가능한 경우 플롯하기가 쉽습니다.

# 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"))) 

더 좋은 줄거리 : 줄의 끝점과 레이블 사이의 간격을 늘리십시오. 다른 옵션은 here을 참조하십시오.

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")) 

enter image description here


질문은 아마도 this one의 중복입니다.

+0

샌디 감사합니다. 그것은 나를 위해 작동합니다. 나는 first.points와 last.points를 알지 못했다. 사소한 수정 : 패키지 이름에 오타가 있습니다. – user6296218

+0

죄송합니다. 고정 생각. –