ggplot 绘图轴分别标记和标签 [英] ggplot plot axis ticks and labels separately

查看:53
本文介绍了ggplot 绘图轴分别标记和标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for a way to create ticks and labels in different positions on a 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)

在此图中,默认情况下刻度和标签位于同一位置(由中断定义).由于主题,x 轴线完全丢失.

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)

以及这些位置的标签

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

最终是一个类似于下图所示的带有部分 x 轴线或完整 x 轴线的图形:

And eventually a figure something like one shown below with partial x-axis line or full x-axis line:

这让我的标签就位

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?

推荐答案

最接近您想要的输出的是:

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

这篇关于ggplot 绘图轴分别标记和标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆