2012-07-17 374 views
3

我使用ggplot2和geom_line()圖中的直接標籤包,我希望其中一個標籤可以讀取「X-M」。但是,在我的data.frame()「X-M」列名稱被重命名爲「X.M」,並且我無法找到有關如何使用自定義標籤名稱提供direct.label函數的文檔,也沒有閱讀源代碼的幫助信息。 (directabels似乎並沒有兌現在ggplot規模,這是我想的第一件事就是設定的標籤名稱。)如何使用ggplot2 +直接標籤的標籤的自定義名稱

示例代碼:

library("scales") 
library("reshape2") 
library("ggplot2") 
library("directlabels") 

data = data.frame(
    C = c(1.2, 1.4, 0.3, -2.0, 0.5), 
    I = c(1.2, 1.5, -1.3, -3.8, 1.8), 
    G = c(0.2, 0.3, 0.3, 0.2, 0.2), 
    "X-M" = c(2.9, -0.7, 0.3, -2.8, 1.5) + 
      c(-2.7, 0.2, 0.4, 3.6, -2.4), 
    year = c("2006", "2007", "2008", "2009", "2010")) 

p <- ggplot(data = melt(data), aes(year, value, color = variable)) + 
    geom_line(aes(group = variable)) + 
    scale_color_hue(breaks = c("C", "I", "G", "X.M"), 
        labels = c("C", "I", "G", "X-M")) # directlabels doesn't 
                # use this 

# Compare: 
p 

# with: 
direct.label(p, list(last.points, hjust = -0.25)) 

產生的圖形可以看出here。帶有直接標籤的人使用「X.M」而不是「X-M」。提前謝謝了!

+0

+1的可重複的例子。歡迎來到SO。 – Andrie 2012-07-17 23:07:54

回答

3

程序包directlabels似乎從您的數據中的列名獲取標籤。

這意味着您必須確保您的標籤在開始的數據中是正確的。要做到這一點,你必須設置check.names=FALSE當您創建data.frame

data = data.frame(
    C = c(1.2, 1.4, 0.3, -2.0, 0.5), 
    I = c(1.2, 1.5, -1.3, -3.8, 1.8), 
    G = c(0.2, 0.3, 0.3, 0.2, 0.2), 
    "X-M" = c(2.9, -0.7, 0.3, -2.8, 1.5) + 
    c(-2.7, 0.2, 0.4, 3.6, -2.4), 
    year = c("2006", "2007", "2008", "2009", "2010"), 
    check.names=FALSE) 

data 
    C I G X-M year 
1 1.2 1.2 0.2 0.2 2006 
2 1.4 1.5 0.3 -0.5 2007 
3 0.3 -1.3 0.3 0.7 2008 
4 -2.0 -3.8 0.2 0.8 2009 
5 0.5 1.8 0.2 -0.9 2010 

現在劇情:

p <- ggplot(data = melt(data), aes(year, value, color = variable)) + 
    geom_line(aes(group = variable)) 
direct.label(p, list(last.points, hjust = -0.25)) 

enter image description here

+0

非常好,完美的作品,謝謝!我完全錯過了data.frame()中的check.names! – Dato 2012-07-17 23:06:22