修改x轴刻度标签

时间:2013-07-17 15:39:14

标签: r ggplot2

我正在尝试更改由ggplot2生成的箱形图的x轴刻度标签。 x轴是一个分类变量(HabFac),我想要的是将其刻度改为6化学品(A-E)。以下是我的代码:

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

1 个答案:

答案 0 :(得分: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))])