2013-07-17 356 views
0

我正在嘗試更改由ggplot2生成的箱形圖的x軸刻度標籤。 X軸是一個分類變量(HabFac),我想要的是將其刻度更改爲6種化學品(A-E)。以下是我的代碼:修改x軸刻度標籤

raw_data=read.table(##Read data##) 

p_TT=ggplot(raw_data, aes(x= HabFac , y = logTissueConc, fill = Chemical)) + geom_boxplot() 

###find out x axis breaks 
dd_TT=ggplot_build(p_TT) 
dd_TT$data[[1]]$x 

##Modify the x ticks 
p_TT=p_TT+ 
scale_x_discrete(breaks=dd_TT$data[[1]]$x, labels = letters[1:7]) 

但是,我的代碼不工作....任何人都可以給我一些建議嗎?

 Species  Chemical logTissueConc HabFac 
1 Barking treefrog A -1.10922426 Arboreal 
2 Barking treefrog A -1.55698525 Arboreal 
3 Barking treefrog A  -0.67977088 Arboreal 
4 Barking treefrog A -1.22868756 Arboreal 
5 Barking treefrog A -0.47476868 Arboreal 
6 Barking treefrog B -0.89399639 Arboreal 
7 Barking treefrog B -1.35670286 Arboreal 
8 Barking treefrog B -2.35421158 Arboreal 
9 Barking treefrog B -2.49491771 Arboreal 
10 Barking treefrog B -2.30921816 Arboreal 
11 Barking treefrog C 2.06394108 Arboreal 
12 Barking treefrog C 1.84732292 Arboreal 
13 Barking treefrog C 1.62127641 Arboreal 
14 Barking treefrog C 1.72991810 Arboreal 
15 Barking treefrog C 1.72845824 Arboreal 
16 Barking treefrog C -0.42136482 Arboreal 
17 Barking treefrog C -0.03384518 Arboreal 
18 Barking treefrog C -0.76756916 Arboreal 
19 Barking treefrog C -0.77322993 Arboreal 
20 Barking treefrog C -1.20469607 Arboreal 
21 Barking treefrog D -1.31449937 Arboreal 
22 Barking treefrog D -1.52823116 Arboreal 
23 Barking treefrog D -1.94002471 Arboreal 
24 Barking treefrog D -1.29272381 Arboreal 
25 Barking treefrog D -1.75399776 Arboreal 
26 Cricket frog A -1.37352233 Aquatic 
27 Cricket frog A -0.83291030 Aquatic 
28 Cricket frog A -0.98828589 Aquatic 
29 Cricket frog A -1.08040579 Aquatic 
30 Cricket frog A -1.28747727 Aquatic 
31 Cricket frog E 0.73098756 Aquatic 
32 Cricket frog E 0.56309363 Aquatic 
33 Cricket frog E 0.55666185 Aquatic 
34 Cricket frog E 0.37853050 Aquatic 
35 Cricket frog E 0.31730552 Aquatic 

回答

3

您需要提供一個將現有標籤映射到新標籤的labels參數的功能。考慮以下幾點:

qplot(Species,Petal.Length,data=iris)+scale_x_discrete(labels=toupper) 

更直接地回答你的問題,你需要構建從數據中現有的標籤映射到一個位置,在您的新標籤的載體的功能。如果您現有的數據是factor,您可以使用類似的東西:

qplot(Species,Petal.Length,data=iris)+scale_x_discrete(labels=function(x) letters[1:3][which(x==levels(iris$Species))]) 
+0

感謝您的建議。這就像重新映射,對吧?我可否知道如何增加刻度標籤的數量?以前,我有兩個,但我現在需要七.. –

+0

@ tao.hong請參閱:http://stackoverflow.com/a/16789128/269476 – James

+0

謝謝!問題解決了! –