如何在ggplot2中的轴上绘制单个值?

时间:2019-02-16 21:16:14

标签: r ggplot2 axis

我想创建一个情节,类似于以下内容:

set.seed(8)
xpos<-rep(1:4,2)
sample<-rep(c("One Stage","Two Stage"),each=4)
dat<-data.frame(cbind(xpos,choice,sample))
dat$xpos<-as.integer(dat$xpos)
dat$choice<-(c(.2,.4,.3,.22,.17,.03,.081,.035))
dat$sample<-as.character(dat$sample)

ggplot(data=dat, aes(x=xpos, y=choice, group=sample, shape=factor(sample), colour=factor(sample))) + 
  geom_line(aes(linetype=factor(sample)))+
  geom_point(size=3)+
  geom_point(aes(x=1, y=0.5),size=3)+
  scale_linetype_manual(values=c("longdash", "dotted"))+
  scale_x_continuous("Block", breaks=seq(1,4,1),limits=c(0.8,4.2))+
  scale_y_continuous("Choice Rates", breaks=seq(0,1,0.2),limits=c(-0.02,1))+
  theme_classic(base_size = b.size)+
  labs(title="Model predictions" )+ theme(plot.title = element_text(hjust=0.5))+
  theme(legend.title =element_blank(),legend.position=c(.8,.85)) + scale_color_grey(start=0.2, end=0.2)

这是图形的样子: enter image description here

现在,我希望单点显示在Y轴上。

我知道我应该为此更改“ scale_x_continuous”限制(从0.8到0),但是随后得到以下图形,这不是我想要的:

enter image description here

该怎么办?

这是最终的通缉结果: enter image description here

由于下面的评论,我意识到了如何做到:

 ggplot(data=dat, aes(x=xpos, y=choice, group=sample, shape=factor(sample), 
  colour=factor(sample))) + 
  geom_line(aes(linetype=factor(sample)))+
  geom_point(size=3)+
  geom_point(aes(x=0.8, y=0.5),size=3)+
  scale_linetype_manual(values=c("longdash", "dotted"))+
  scale_x_continuous("Block", breaks=seq(1,4,1),limits=c(0.8,4.2),expand=c(0,0))+
  coord_cartesian(clip = 'off') +
  scale_y_continuous("Checking Rates", breaks=seq(0,1,0.2),limits=c(-0.02,1))+
  theme_classic(base_size = b.size)+
  labs(title="Model predictions" )+ theme(plot.title = element_text(hjust=0.5))+
  theme(legend.title =element_blank(),legend.position=c(.8,.85)) + scale_color_grey(start=0.2, end=0.2)

1 个答案:

答案 0 :(得分:2)

您应该在expand = c(0,0))scale_x_continuous,并添加coord_cartesian(clip = 'off'),以免截断点(形状的一半落在绘图区域之外)。

ggplot(data=dat, aes(x=xpos, y=choice, group=sample, shape=factor(sample), colour=factor(sample))) + 
  geom_line(aes(linetype=factor(sample)))+
  geom_point(size=3)+
  geom_point(aes(x=1, y=0.5),size=3)+
  scale_linetype_manual(values=c("longdash", "dotted"))+
  scale_x_continuous("Block", breaks=seq(1,4,1),
    limits=c(1,4.2), expand = c(0,0))+
  coord_cartesian(clip = 'off') +
  scale_y_continuous("Choice Rates", breaks=seq(0,1,0.2),limits=c(-0.02,1))+
  labs(title="Model predictions" )+ theme(plot.title = element_text(hjust=0.5))+
  theme(legend.title =element_blank(),legend.position=c(.8,.85)) + 
  scale_color_grey(start=0.2, end=0.2) +
  theme_classic()

enter image description here