2016-09-28 45 views
1

標題說明了一切:我想在ggplot中的垂直線的標籤上使用上標。 這裏是一個不太漂亮的例子:R:在geom_vline標籤上標

df <- data.frame(x = c(1:10),y = c(2,2,3,4,5,5,6,7,5,4)) 

ggplot(data=df, aes(x,y, group=1)) + 
    geom_line() + 
    scale_x_reverse() + 
    geom_vline(xintercept=3) + 
    geom_text(aes(x=3, label=paste("3400","cm","^-1", sep=""), y=5), angle=90, vjust = 1.2) 

我想-1上標。有很多解決方案都可以在繪圖軸標籤上做到這一點,但是它們都不在這裏工作。有人可以幫忙嗎?

回答

3

你太親近了!您只需在geom_text中設置parse=TRUE並使用?plotmath語法。

df <- data.frame(x = c(1:10),y = c(2,2,3,4,5,5,6,7,5,4)) 

library(ggplot2) 
ggplot(data=df, aes(x,y, group=1)) + 
    geom_line() + 
    scale_x_reverse() + 
    geom_vline(xintercept=3) + 
    #geom_text(data = data.frame(x = 3, y = 5), label = paste("paste(3400, cm)","^-1", sep=""), 
    # angle=90, parse = TRUE, vjust = 1.2) + 
    annotate("text", x = 3, y = 5, angle = 90, label = paste("paste(3400, cm)","^-1", sep=""), 
    vjust = 1.2, parse = TRUE) 

結果:

enter image description here

另外,注意文字較少模糊比你的代碼。這是因爲你的代碼實際上是在相同的座標下打印標籤10次。您需要使geom_text使用不同的數據或更好的使用annotate

+0

也可以使用:https://github.com/hadley/ggplot2/wiki/Plotmath –

+0

@Chrisss非常感謝! – Anca

+0

我會看看情節,謝謝你的建議! – Anca