0

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

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
4

1 回答 1

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))])
于 2013-07-17T15:46:52.963 回答