【问题标题】:Two different plots from different libraries on the same page同一页面上来自不同库的两个不同图
【发布时间】:2019-02-21 15:51:41
【问题描述】:

我有一个来自 lattice 库的图(水平图)和一个来自 oce 库的棒图,我想将它们堆叠在一起。我在堆叠这些图时遇到了问题,就像我通常使用基础 R 一样,我认为这是因为它们都是专门的图。是否可以将以下两个图堆叠在同一页面上,以使时间戳(x 轴)彼此对齐?

library(oce)
library(lattice)
library(grid)

第一个绘图(来自 OCE 帮助文档的示例)

# Oceanographic example
data(met)
t <- met[["time"]]
u <- met[["u"]]
v <- met[["v"]]
p <- met[["pressure"]]

dev.new(width=15, height=4)
plotSticks(t, 99, u, v, yscale=25)

第二个情节:

AllT<-NULL
for(i in seq(1,length(t))){

    myTime<-t[i]
    myTime2<-rep(myTime,10)
    AllT<-append(AllT,myTime2)      
}

myY<-NULL
for(j in seq(1,length(t))){
    mySeq<-seq(1,10)
    myY<-append(myY,mySeq)    
}

Temp<-seq(1,7200)


MyDF<-data.frame(Temp,myY,AllT)



#Plot code
dev.new(width=15, height=6)
p1<-levelplot(Temp ~ AllT * myY,
    data = MyDF,ylim=c(10,1),
    xlab = "Time", ylab = "y]",
    aspect=0.4,
    )

p1

trellis.focus("legend", side="right", clipp.off=TRUE, highlight=FALSE)
grid.text('[Temp]', 1.9, .5, hjust=0.5, vjust=1,rot=270)
trellis.unfocus()

理想情况下,最终图的顶部应该是棒图(如果 x 轴对齐,则棒图上不需要刻度标签),下面的水平图之间的空间最小

【问题讨论】:

  • 我希望ggplotify 能够将绘图转换为grobs,但我认为它不能。 OCE 往往非常独特,因为它处理的数据,可能是因为它所有的 S4 对象。以grobs 的形式获取图将很容易满足您的需求。
  • 除了使用 oce 之外,我还没有找到一种方法来绘制这种风速/风向,所以我现在只能使用这个库

标签: r plot lattice


【解决方案1】:

这是我现在能想到的最好的了。必须有一种方法来实际修改grobs,就像我知道的那样,但是当我尝试时它不喜欢gTrees。所以这会让你接近。

这些链接可能有些用处。

https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/

force a regular plot object into a Grob for use in grid.arrange

#libraries
library(gridGraphics)
library(grid)
library(gridExtra)
library(oce)
library(gggplot2)
library(ggplotify)

#plots
data(met)
t <- met[["time"]]
u <- met[["u"]]
v <- met[["v"]]
p <- met[["pressure"]]

grab_grob <- function(){
  grid.echo()
  grid.grab()
  }

plotSticks(t, 99, u, v, yscale=25)
p1 <- grab_grob() #grab the last plot as a grob

AllT <- NULL
for(i in seq(1, length(t))){
  myTime <- t[i]
  myTime2 <- rep(myTime, 10)
  AllT <- append(AllT, myTime2)      
}

myY <- NULL
for(j in seq(1, length(t))){
  mySeq <- seq(1, 10)
  myY <- append(myY, mySeq)    
}

Temp <- seq(1, 7200)

MyDF <- data.frame(Temp, myY, AllT)

#Plot code
dev.new(width = 15, height = 6)
p2 <- levelplot(Temp ~ AllT * myY,
          data = MyDF, ylim=c(10, 1),
          xlab = "Time", ylab = "y]",
          aspect = 0.4,
)

p2

trellis.focus("legend", side="right", clipp.off = TRUE, highlight = FALSE)
grid.text('[Temp]', 1.9, .5, hjust = 0.5, vjust = 1, rot = 270)
trellis.unfocus()

p2a <- as.grob(p2)

grid.arrange(p1, p2a, ncol = 1)

【讨论】:

    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多