双重" y" ggplot2图中的轴

时间:2017-11-30 08:41:05

标签: r plot ggplot2

我知道这个主题已经在本页的不同主题中出现了一段时间,但我担心按照所有这些主题的说明我还没有设法修复它。我一直试图解决这个问题一个星期似乎很微不足道,我找不到方法。

我不知道它是关于图形的差异还是我做错了。案例如下。我有两个使用ggplot2包的图形:

library(ggplot2)
data<-data.frame(Age=0,var2=0,var1=0,inf=0,sup=0,ppv=0)
data[1,]<-c(1,1,0.857,0.793,0.904,0.03)
data[2,]<-c(1,2,0.771   ,0.74,0.799,0.056)
data[3,]<-c(1,3,0.763   ,0.717,0.804,0.06) 
data[4,]<-c(1,4,0.724   ,0.653,0.785,0.09)
data[5,]<-c(2,1,0.906,0.866,0.934,0.055)
data[6,]<-c(2,2,0.785   ,0.754,0.813,0.067)
data[7,]<-c(2,3,0.660,0.593,0.722,0.089)
data[8,]<-c(2,4,0.544,0.425,0.658,0.123)

pd <- position_dodge(0.2) # 
names(data)<-c("Age","var2","var1","inf","sup","ppv")
data$Age<-as.character(data$Age)
data$var2<-as.character(data$var2)
p<- ggplot(data, aes(x=var2, y=var1, colour=Age)) + 
  geom_errorbar(aes(ymin=inf, ymax=sup), width=.1 , position=pd) +
  geom_line(position=pd,aes(group=Age),linetype=c("dashed")) +
  geom_point(position=pd,size=3)   +
  theme_light()+
  ylim(0,1) +
  scale_color_manual(values=c("1"="grey55","2"="grey15"))+guides(fill=guide_legend(nrow=2,byrow=TRUE) 
  )
s<- ggplot(data, aes(x=var2, y=ppv, colour=Age)) + 
  geom_line(position=pd,aes(group=Age),linetype=c("dashed")) +
  geom_point(position=pd,size=3)   +
  theme_light()+
  ylim(0,0.2) +      scale_color_manual(values=c("1"="grey55","2"="grey15"))+guides(fill=guide_legend(nrow=2,byrow=TRUE) 
  )

他们看起来像这样:

p 的图片 enter image description here

s的图像 enter image description here

我想知道是否有人会知道将它们组合在一个图表中的方式,它们具有它们当前具有的两个比例,例如,图左侧的y轴和左侧的y轴。图表在右侧,因为我无法直接在图表中绘制两个数据,因为尺度存在根本差异。

非常感谢你的时间,

致以最诚挚的问候,

1 个答案:

答案 0 :(得分:2)

尝试此代码,您应该在新图层设置aes

ggplot(data, aes(x = var2, y = var1, colour=Age)) + 
  geom_errorbar(aes(ymin = inf, ymax = sup), width = .1, position = pd) +
  geom_line(position = pd, aes(group = Age), linetype = c("dashed")) +
  geom_point(position = pd, size = 3) +
  geom_line(position = pd, aes(x = var2, y = ppv * 5, colour = Age, group = Age), linetype = c("dashed"), data = data) +
  geom_point(aes(x = var2, y = ppv * 5, colour = Age, group = Age), position = pd, size = 5) +
  theme_light() +
  scale_color_manual(values = c("1" = "grey55", "2" = "grey15")) + 
  scale_y_continuous(sec.axis = sec_axis(~./5)) +
  guides(fill = guide_legend(nrow = 2, byrow = TRUE))

enter image description here