问题
my data in R is look like this:
1-12 1-12 1-15 1-15 1-20 1-20 2-6 2-6 3-1-1 3-1-1 3-1 3-1 3-2 3-2 3-3 3-3
N 0 0 14 0 17 0 9 0 27 0 9 0 13 0 33 0
P 0 0 0 12 0 12 0 5 0 13 0 6 0 0 0 9
F 0 0 0 0 0 0 0 2 0 14 0 0 0 6 0 20
By dput(data) the result in R is:
structure(c(0L, 0L, 0L, 0L, 0L, 0L, 14L, 0L, 0L, 0L, 12L, 0L,
17L, 0L, 0L, 0L, 12L, 0L, 9L, 0L, 0L, 0L, 5L, 2L, 27L, 0L, 0L,
0L, 13L, 14L, 9L, 0L, 0L, 0L, 6L, 0L, 13L, 0L, 0L, 0L, 0L, 6L,
33L, 0L, 0L, 0L, 9L, 20L), .Dim = c(3L, 16L), .Dimnames = list(
c("N", "P", "F"), c("1-12", "1-12", "1-15", "1-15", "1-20",
"1-20", "2-6", "2-6", "3-1-1", "3-1-1", "3-1", "3-1", "3-2",
"3-2", "3-3", "3-3")))
and my code is:
barplot(data,space=c(1,0.25),legend=rownames(data),col=c('white','black','grey'),las=2)
it looks like a normal bar plot, each column has a label at the bottom...
But, there are too many labels in the x-axis, and I want to merge the names of two columns into one(since they have the same name), i.e, in the middle of first two columns, there is only one label "1-12" at the bottom, so there will be eight labels in total. How can I make this change?
Many thanks!
回答1:
If you just wish to have the centred labels under each group, you could do something like:
# suppress the x-axis and save your original plot's bar locations
bp <- barplot(data,space=c(1,0.25),legend=rownames(data),
col=c('white','black','grey'),las=2,
xaxt="n")
# draw a new axis using these values
axis(1,at=rowMeans(matrix(bp,ncol=2,byrow=TRUE)),
labels=unique(colnames(data)),lty=0)

Ignoring the overlapping legend of course... which can be fixed by placing it better using legend.args
in the original barplot
call
来源:https://stackoverflow.com/questions/18264135/how-to-merge-column-labels-in-barplot-in-r-a-stacked-barplot