首页 文章

ggplot plot轴分别标记和标签

提问于
浏览
2

我正在寻找一种在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 回答

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

相关问题