问题
I am looking for a way to create ticks and labels in different positions on a ggplot.
Sample code
#load libraries
library(ggplot2)
library(reshape2)
#create data
df <-data.frame(A=1:6,B=c(0.6,0.5,0.4,0.2,0.3,0.8),C=c(0.4,0.5,0.6,0.8,0.7,0.2),D=c("cat1","cat1","cat1","cat2","cat2","cat2"))
df
df1 <- melt(df,measure.vars=c("B","C"))
#plot
p <- ggplot()+
geom_bar(data=df1,aes(x=A,y=value,fill=variable),stat="identity")+
theme(axis.title=element_blank(),legend.position="none")
print(p)
In this figure, the default has the ticks and labels at same position (defined by breaks). And the x axis line is missing altogether due to the theme.
Instead, I would like to have ticks at these positions
tpoint <- c(1,3,4,6)
and labels at these positions
lpoint <- data.frame(pos=c(2,5),lab=c("cat1","cat2"))
And eventually a figure something like one shown below with partial x-axis line or full x-axis line:
This puts my labels in place
p1 <- p + scale_x_discrete(breaks=lpoint$pos,labels=lpoint$lab)
But the ticks are in the wrong place and multiple scales are not possible?
回答1:
The closest I could come to your desired output is this:
dfannotate <- data.frame(x = c(2, 5), xmin = c(1, 4), xmax = c(3, 6), y = -.01, height=.02)
dfbreaks = data.frame(lim = 1:6, lab = c('', 'cat1', '', '', 'cat2', ''))
p + geom_errorbarh(data = dfannotate, aes(x, y, xmin=xmin, xmax=xmax, height=height)) +
scale_x_discrete(limits=dfbreaks$lim, labels=dfbreaks$lab) +
scale_y_continuous(expand = c(0, 0), limits=c(-0.02, 1.02)) +
theme(axis.ticks.x = element_line(linetype=0))
来源:https://stackoverflow.com/questions/28263721/ggplot-plot-axis-ticks-and-labels-separately