Reputation: 4434
I am trying to change x axis tick labels of a box-plot generated by ggplot2
. The x axis is a categorical variable (HabFac), what I want is to change its ticks to 6 Chemicals (A-E). Below is my code:
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])
However, my code does not work.... Can anyone give me some suggestions?
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
Upvotes: 0
Views: 973
Reputation: 66874
You need to provide a function to the labels
argument that maps the existing labels to new ones. Consider the following:
qplot(Species,Petal.Length,data=iris)+scale_x_discrete(labels=toupper)
To answer your question more directly, you would need to construct a function that maps the existing label from the data to a position in a vector of your new labels. If your existing data is a factor
you could use something like:
qplot(Species,Petal.Length,data=iris)+scale_x_discrete(labels=function(x) letters[1:3][which(x==levels(iris$Species))])
Upvotes: 3