【问题标题】:Getting LaTeX into R Plots将 LaTeX 放入 R 图中
【发布时间】:2010-11-26 13:50:43
【问题描述】:

我想使用base/latticeggplot2 的组合将LaTeX 排版添加到R 中的绘图元素(例如:标题、轴标签、注释等)。

问题:

  • 有没有办法使用这些包将LaTeX 放入绘图中,如果是这样,它是如何完成的?
  • 如果没有,是否需要额外的软件包来完成此操作。

例如,Python matplotlib 通过text.usetex 包编译LaTeX,如下所述:http://www.scipy.org/Cookbook/Matplotlib/UsingTex

R中是否有类似的过程可以生成这样的图?

【问题讨论】:

标签: r latex plot


【解决方案1】:

The CRAN package latex2exp 包含一个 TeX 函数,可将 LaTeX 公式转换为 R 的绘图表达式。您可以在任何可以输入数学注释的地方使用它,例如轴标签、图例标签和一般文本。

例如:

x <- seq(0, 4, length.out=100)
alpha <- 1:5

plot(x, xlim=c(0, 4), ylim=c(0, 10), 
     xlab='x', ylab=TeX('$\\alpha  x^\\alpha$, where $\\alpha \\in 1\\ldots 5$'), 
     type='n', main=TeX('Using $\\LaTeX$ for plotting in base graphics!'))

invisible(sapply(alpha, function(a) lines(x, a*x^a, col=a)))

legend('topleft', legend=TeX(sprintf("$\\alpha = %d$", alpha)), 
       lwd=1, col=alpha)

产生this plot

【讨论】:

  • 这太棒了!你能解释一下大约是什么意思吗?它是如何工作的?
  • 大约,我的意思是 LaTeX 字符串被翻译成 R 的 plotmath 表达式——这意味着如果 plotmath 不支持特定的 LaTeX 符号,它要么不会被渲染,要么会通过组合来渲染可用的符号。
  • 虽然不是很好。看起来很恶心,它只支持有限数量的符号。更糟糕的是,似乎没有任何东西有助于“出版质量”的情节(人们错误地声称 R 能够做到这一点)。我猜是时候学习 Python 了..
  • 剧情链接已断开:/
【解决方案2】:

这是一个使用ggplot2的示例:

q <- qplot(cty, hwy, data = mpg, colour = displ)
q + xlab(expression(beta +frac(miles, gallon)))

【讨论】:

  • 不幸的是,它几乎没有 LaTeX 的功能。
  • 现在情况如何?我认为它在 R 3.1.1 中有所改进。
【解决方案3】:

h <- rnorm(mean = 5, sd = 1, n = 1000) hist(h, main = expression(paste("Sampled values, ", mu, "=5, ", sigma, "=1")))

取自这里https://stats.idre.ucla.edu/r/codefragments/greek_letters/的一篇非常有帮助的文章

【讨论】:

    【解决方案4】:

    这是我自己的实验室报告中的一些内容。

    • tickzDeviceLaTeX导出tikz图像
    • 注意,在某些情况下,"\\" 变为 "\""$" 变为 "$\",如下 R 代码所示:"$z\\frac{a}{b}$" -&gt; "$\z\frac{a}{b}$\"

    • xtable 还可以将表导出到乳胶代码

    代码:

    library(reshape2)
    library(plyr)
    library(ggplot2)
    library(systemfit)
    library(xtable)
    require(graphics)
    require(tikzDevice)
    
    setwd("~/DataFolder/")
    Lab5p9 <- read.csv (file="~/DataFolder/Lab5part9.csv", comment.char="#")
    
    AR <- subset(Lab5p9,Region == "Forward.Active")
    
    # make sure the data names aren't already in latex format, it interferes with the ggplot ~  # tikzDecice combo
    colnames(AR) <- c("$V_{BB}[V]$", "$V_{RB}[V]$" ,  "$V_{RC}[V]$" , "$I_B[\\mu A]$" , "IC" , "$V_{BE}[V]$" , "$V_{CE}[V]$" , "beta" , "$I_E[mA]$")
    
    # make sure the working directory is where you want your tikz file to go
    setwd("~/TexImageFolder/")
    
    # export plot as a .tex file in the tikz format
    tikz('betaplot.tex', width = 6,height = 3.5,pointsize = 12) #define plot name size and font size
    
    #define plot margin widths
    par(mar=c(3,5,3,5)) # The syntax is mar=c(bottom, left, top, right).
    
    ggplot(AR, aes(x=IC, y=beta)) +                                # define data set 
        geom_point(colour="#000000",size=1.5) +                # use points
        geom_smooth(method=loess,span=2) +                     # use smooth
        theme_bw() +                    # no grey background
        xlab("$I_C[mA]$") +                 # x axis label in latex format
        ylab ("$\\beta$") +                 # y axis label in latex format
        theme(axis.title.y=element_text(angle=0)) + # rotate y axis label
        theme(axis.title.x=element_text(vjust=-0.5)) +  # adjust x axis label down
        theme(axis.title.y=element_text(hjust=-0.5)) +  # adjust y axis lable left
        theme(panel.grid.major=element_line(colour="grey80", size=0.5)) +# major grid color
        theme(panel.grid.minor=element_line(colour="grey95", size=0.4)) +# minor grid color 
        scale_x_continuous(minor_breaks=seq(0,9.5,by=0.5)) +# adjust x minor grid spacing
        scale_y_continuous(minor_breaks=seq(170,185,by=0.5)) + # adjust y minor grid spacing
        theme(panel.border=element_rect(colour="black",size=.75))# border color and size
    
    dev.off() # export file and exit tikzDevice function
    

    【讨论】:

      【解决方案5】:

      我只有一个解决方法。可以先生成一个 eps 文件,然后使用 eps2pgf 工具将其转换回 pgf。见http://www.texample.net/tikz/examples/eps2pgf/

      【讨论】:

        【解决方案6】:

        这是一个很酷的函数,可让您使用绘图功能,但表达式存储为字符模式的对象。这使您可以使用粘贴或正则表达式函数以编程方式操作它们。我不使用 ggplot,但它也应该在那里工作:

            express <- function(char.expressions){
               return(parse(text=paste(char.expressions,collapse=";")))
            }
            par(mar=c(6,6,1,1))
            plot(0,0,xlim=sym(),ylim=sym(),xaxt="n",yaxt="n",mgp=c(4,0.2,0),
               xlab="axis(1,(-9:9)/10,tick.labels,las=2,cex.axis=0.8)",
               ylab="axis(2,(-9:9)/10,express(tick.labels),las=1,cex.axis=0.8)")
            tick.labels <- paste("x >=",(-9:9)/10)
            # this is what you get if you just use tick.labels the regular way:
            axis(1,(-9:9)/10,tick.labels,las=2,cex.axis=0.8)
            # but if you express() them... voila!
            axis(2,(-9:9)/10,express(tick.labels),las=1,cex.axis=0.8)
        

        【讨论】:

          【解决方案7】:

          几年前我通过输出为 .fig 格式而不是直接输出为 .pdf 来做到这一点;您编写包含乳胶代码的标题并使用 fig2ps 或 fig2pdf 创建最终的图形文件。我必须这样做的设置与 R 2.5 不同;如果我不得不再做一次,我会转而研究 tikz,但无论如何我都会把它作为另一个潜在的选择。

          关于我如何使用 Sweave 的笔记在这里:http://www.stat.umn.edu/~arendahl/computing

          【讨论】:

            【解决方案8】:

            盗自here,以下命令正确使用LaTeX绘制标题:

            plot(1, main=expression(beta[1]))
            

            更多详情请见?plotmath

            【讨论】:

            • 有趣,demo(plotmath) 也很好用所以数学符号必须通过 plotmath 的语法重新解释?这似乎是一种光荣的浪费时间,特别是如果你有一个涉及的 LaTeX 表达式。这就是为什么我喜欢 matplotlib 自己编译 LaTeX 的能力。有什么东西可以使用 LaTeX 并生成 plotmath 语法吗?
            • 我不知道。 RWiki 上有一篇关于让乳胶与 ggplot2 一起工作的有趣帖子:wiki.r-project.org/rwiki/…
            【解决方案9】:

            您可以从 R 生成 tikz 代码: http://r-forge.r-project.org/projects/tikzdevice/

            【讨论】:

            • 我刚刚发现这个包已经从 CRAN 中删除了。
            • 该软件包似乎仍可在 r-forge 获得。此外,它可在此处获得:github.com/Sharpie/RTikZDevice
            猜你喜欢
            • 2018-10-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-04-08
            • 2016-10-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多