ggplot plot轴分别标记和标签

时间:2015-02-01 14:23:29

标签: r plot ggplot2 r-grid

我正在寻找一种在ggplot上的不同位置创建刻度和标签的方法。

示例代码

#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)

enter image description here

在此图中,默认值具有相同位置的刻度和标签(由间隔定义)。由于主题,x轴线完全缺失。

相反,我想在这些位置上打勾

tpoint <- c(1,3,4,6)

和这些位置的标签

lpoint <- data.frame(pos=c(2,5),lab=c("cat1","cat2"))

最终形成如下图所示的图,其中部分x轴线或完整的x轴线:

enter image description here

这会使我的标签到位

p1 <- p + scale_x_discrete(breaks=lpoint$pos,labels=lpoint$lab)

但是滴答声是在错误的地方,并且不可能有多种尺度?

1 个答案:

答案 0 :(得分:3)

最接近我想要的输出是:

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))
相关问题