2014-04-14 118 views
2

如何使用ggplot添加數據標籤到點?GGplot添加數據標籤到點

我呼籲堆疊數據幀「堆疊」:

> head(stacked) 
    time value variable 
1 100 152.2211  gg 
2 110 146.3304  gg 
3 115 143.5831  gg 
4 120 140.9527  gg 
5 125 138.4297  gg 
6 130 136.0057  gg 

> tail(stacked) 
     time value variable 
    755 1975 56.02922  t 
    756 1980 56.14049  t 
    757 1985 56.25148  t 
    758 1990 56.36219  t 
    759 1995 56.47262  t 
    760 2000 56.58277  t 

現在可以說,我想顯示數據標籤顯示「值」字段,其中時間字段等於100。這裏是我的有:

g<- ggplot(stacked, aes(x = time, y=value, colour=variable, group= variable))  + geom_line() + 
geom_text(data = stacked[stacked$time == 100,], aes(label = stacked$value)) 
print(g) 

我收到錯誤:

Error: Aesthetics must either be length one, or the same length as the dataProblems:time, value, variable, variable 

任何想法?

謝謝。

回答

8

問題是,在您的aes(...)呼叫geom_text您正在設置label = stacked$value。您已經指定了數據子集(data = stacked[stacked$time == 100,]),因此您需要在此處執行的操作爲aes(label = value),因此需要value列。

我沒有你的測試數據,但是看看這個例子,我在那是10

ggplot(cars, aes(x = speed, y = dist)) + 
    geom_point() + 
    geom_text(data = subset(cars, speed %% 5 == 0), aes(label = dist)) 
多的速度添加標籤只需要數據點