R语言 在ggplot中为矩阵添加数学符号

f8rj6qna  于 2023-09-27  发布在  其他
关注(0)|答案(3)|浏览(116)

我想知道是否有一种方法可以写出矩阵的表达式,例如矩阵2乘2矩阵,并将其显示在图中,就像我在下面的等式中所做的那样:$Y_{ij} = 3+2.5t_{ij} +\epsilon_{ij}$在R.

curve(dnorm, from = -3, to = 3, n = 1000, main = "Normal Probability Density Function")
text(-2, 0.3, expression(f(x) == paste(frac(1, sqrt(2 * pi * sigma^2)),
                                        " ", e^{
                                            frac(-(x - mu)^2, 2 * sigma^2)
                                       })), cex = 1.2)
ggplot() +
 ggtitle(expression(paste(Y[ij] == beta[0]+beta[1]*t[ij] + b[0][i] + epsilon[ij])))
z3yyvxxp

z3yyvxxp1#

要在R图形中包含一些LaTeX代码,请使用tikzDevice包。这里有一个例子。我做了一个函数,方便使用tikzDevice

library(tikzDevice)

#' @title Function to use 'tikzDevice'
#' @param fplot a function without argument which generates a graphic
#' @param filename filename without extension
#' @param outdir output directory
#' @param overwrite whether to overwrite the existing file if there is one
#' @param compile whether to compile the LaTeX file
#' @param format the format of the compiled file: \code{"pdf"}, \code{"ps"} 
#'   or \code{"eps"}
#' @param lua whether to compile with LuaLaTeX, for \code{format="pdf"} only
#' @param clean argument passed to \code{tools::texi2dvi}; see there
#' @param ... arguments passed to \code{tikz}, such as 
#'   \code{packages="\\usepackage{amsysymb}"}
plot2tikz <- function(
    fplot, filename = "Rplot", outdir = getwd(), overwrite = FALSE, 
    compile = TRUE, format = "pdf", lua = FALSE, clean = FALSE, ...) {
  options(tikzMetricsDictionary='.tikzMetrics')
  format <- match.arg(format, choices = c("pdf", "ps", "eps"))
  texfile <- paste0(filename, ".tex")
  owd <- setwd(outdir); on.exit(setwd(owd))
  if(!overwrite && file.exists(texfile)) {
    stop("The LaTeX file already exists.")
  }
  # run the tikz device
  tikzargs <- list(...)
  tikzargs[["packages"]] <- 
    paste0(
      # "\n\\usepackage[utf8]{inputenc}",
      "\n\\usepackage{tikz}",
      "\n\\usetikzlibrary{calc}",
      # "\n\\usepackage[active,tightpage,psfixbb]{preview}",
      # "\n\\PreviewEnvironment{pgfpicture}",
      # "\n\\setlength\\PreviewBorder{10pt}",
       "\n\\usepackage{amsmath}", 
      tikzargs[["packages"]]
    )
  f <- function(...) {
    tikz(
      texfile, 
      standAlone = TRUE, 
      onefile    = TRUE,
      documentDeclaration = "\\documentclass[tikz]{standalone}\n",
      ...
    )
    fplot()
    dev.off()
  }
  do.call(f, tikzargs)
  # compilation 
  if(compile){
    message("Compilation...")
    if(format == "pdf") {
      # pdf compilation
      pdffile <- paste0(filename, ".pdf")
      if(!overwrite && file.exists(pdffile)) {
        stop("The PDF file already exists.")
      }
      if(lua) {
        command <- sprintf("lualatex %s", texfile)
        system(command)
      } else {
        tools::texi2dvi(texfile, pdf = TRUE, clean = clean)
      }
      message(sprintf("Output pdf file: %s", pdffile))
    } else if(format %in% c("ps", "eps")) {
      psfile <- paste0(filename, ".ps")
      if(!overwrite && file.exists(psfile)) {
        stop("The PS file already exists.")
      }
      tools::texi2dvi(texfile, pdf = FALSE, clean = clean)
      command <- sprintf("dvips %s.dvi", filename)
      system(command)
      message(sprintf("Output PS file: %s", psfile))
      if(format == "eps") {
        command <- sprintf("ps2epsi %s.ps %s.epi", filename, filename)
        system(command)
        file.rename(sprintf("%s.epi", filename), sprintf("%s.eps", filename))
        message(sprintf("Output EPS file: %s.eps", filename))
      }
    }
  }
  #
  message(sprintf(
    "Output TEX file: %s", 
    normalizePath(texfile, winslash = .Platform$file.sep)
  ))
  invisible(NULL)
}

# example ####
library(ggplot2)

# make a plot with some LaTeX code
x     <- rnorm(n = 100, mean = 10, sd = 10)
alpha <- 2.0
beta  <- 1.5
gamm  <- 10
err   <- rnorm(n=100, mean=0, sd = 0.25)
f_x   <- alpha / (1 + exp(-1 * beta * (x - gamm))) + err
dat   <- data.frame(x=x, y=f_x)

LaTeX <- "\\Large$\\begin{pmatrix} 1 & 2 \\\\ 3 & 4 \\end{pmatrix}$"

gg <- ggplot(data = dat, aes(x = x, y = y)) + 
  geom_smooth(method = "loess") + 
  geom_point() + 
  geom_text(aes(x = 15, y = 1, label = LaTeX)) +
  theme_classic()

# tikz it!
fplot <- function() {
  print(gg)
}
plot2tikz(
  fplot, overwrite = TRUE, compile = TRUE, format = "pdf",
  width = 5, height = 5
)

whitzsjs

whitzsjs2#

这是一个基本情节的努力。没有矩阵plotmath工具,但您可以使用atop和超大“管道”(|)字符创建一个(或者如果您希望拥有超大弧形围栏,只需选择开括号和闭括号)

plot(1,1,col="transparent")
text(1.2, 0.8, expression( atop(1~2~3,4~5~6) ) )
 text(1.15, .8, labels="|",cex=3 ) #Need to figure out what the coords should be
 text(1.25, .8, labels="|",cex=3 ) and adjust the other side's big-pipe

hgqdbh6s

hgqdbh6s3#

您可以使用gridExtra::tableGrob()绘制一个矩阵,它与ggplot2兼容(grid由ggplot2在后台使用)。使用patchwork软件包,您可以将矩阵与ggplot2图结合起来。

library(patchwork)
library(ggplot2)
library(grid)
library(gridExtra)

matrix_grob <- tableGrob(matrix(1:4, 2, 2))

grid.newpage()
grid.draw(matrix_grob)

plot1 <- ggplot(mtcars, aes(cyl)) + geom_bar()
plot1 + matrix_grob

使用grid::grid.arrange()可以实现许多布局:

grid.arrange(
  grid.arrange(
    textGrob("This is a plot title and to the right is a matrix"),
    matrix_grob,
    ncol = 2,
    widths = c(3, 1),
    heights = 1
  ),
  plot1,
  heights = c(1, 3),
  widths = 1
)

相关问题