将 LaTeX 放入 R 绘图中

发布于 2024-08-03 18:20:00 字数 532 浏览 1 评论 0原文

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

问题:

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

例如,在 Python matplotlib 中,通过 text.usetex 包编译 LaTeX,如下所述: scipy.org/Cookbook/Matplotlib/UsingTex" rel="noreferrer">http://www.scipy.org/Cookbook/Matplotlib/UsingTex

是否有类似的过程可以在 R?

I would like to add LaTeX typesetting to elements of plots in R (e.g: the title, axis labels, annotations, etc.) using either the combination of base/lattice or with ggplot2.

Questions:

  • Is there a way to get LaTeX into plots using these packages, and if so, how is it done?
  • If not, are there additional packages needed to accomplish this.

For example, in Python matplotlib compiles LaTeX via the text.usetex packages as discussed here: http://www.scipy.org/Cookbook/Matplotlib/UsingTex

Is there a similar process by which such plots can be generated in R?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

却一份温柔 2024-08-10 18:20:01

CRAN 包 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(r'($\alpha  x^\alpha$, where $\alpha \in \{1 \ldots 5\}$)'), 
     type='n', main=TeX(r'(Using $\LaTeX$ for plotting in base graphics!)', bold=TRUE))

for (a in alpha) {
  lines(x, a*x^a, col=a)
}

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

生成此图

The CRAN package latex2exp contains a TeX function that translate LaTeX formulas to R's plotmath expressions. You can use it anywhere you could enter mathematical annotations, such as axis labels, legend labels, and general text.

For example:

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

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

for (a in alpha) {
  lines(x, a*x^a, col=a)
}

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

produces this plot.

断桥再见 2024-08-10 18:20:01

以下是使用 ggplot2 的示例:

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

替代文本

Here's an example using ggplot2:

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

alt text

所谓喜欢 2024-08-10 18:20:01

此处窃取,以下命令正确使用 LaTeX 绘制标题:

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

请参阅 ?plotmath 了解更多详细信息。

As stolen from here, the following command correctly uses LaTeX to draw the title:

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

See ?plotmath for more details.

秋心╮凉 2024-08-10 18:20:01

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

  • tickzDeviceLaTeX 导出 tikz 图像
  • 请注意,在某些情况下 "\\" 会变成 "\""$" 变为 "$\",如以下 R 代码所示:"$z\\frac{a} {b}$”-> "$\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

Here's something from my own Lab Reports.

  • tickzDevice exports tikz images for LaTeX
  • Note, that in certain cases "\\" becomes "\" and "$" becomes "$\" as in the following R code: "$z\\frac{a}{b}$" -> "$\z\frac{a}{b}$\"

  • Also xtable exports tables to latex code

The code:

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
剧终人散尽 2024-08-10 18:20:01

这是一个很酷的函数,可让您使用绘图功能,但将表达式存储为字符模式的对象。这使您可以使用粘贴或正则表达式函数以编程方式操作它们。我不使用 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)

Here's a cool function that lets you use the plotmath functionality, but with the expressions stored as objects of the character mode. This lets you manipulate them programmatically using paste or regular expression functions. I don't use ggplot, but it should work there as well:

    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)
|煩躁 2024-08-10 18:20:01

几年前,我通过输出为 .fig 格式而不是直接输出为 .pdf 来做到这一点;您编写包括 Latex 代码在内的标题,并使用Fig2ps 或Fig2pdf 创建最终的图形文件。我必须执行此操作的设置与 R 2.5 不同;如果我必须再次这样做,我会改为查看 tikz,但无论如何我都会将其作为另一个潜在的选择包含在这里。

我关于如何使用 Sweave 做到这一点的注释如下:http://www.stat.umn。 edu/~arendahl/计算

I did this a few years ago by outputting to a .fig format instead of directly to a .pdf; you write the titles including the latex code and use fig2ps or fig2pdf to create the final graphic file. The setup I had to do this broke with R 2.5; if I had to do it again I'd look into tikz instead, but am including this here anyway as another potential option.

My notes on how I did it using Sweave are here: http://www.stat.umn.edu/~arendahl/computing

旧城烟雨 2024-08-10 18:20:01

h <- rnorm(均值 = 5,sd = 1,n = 1000)
hist(h, main = 表达式(paste("采样值,", mu, "=5, ", sigma,
"=1")))

摘自此处的一篇非常帮助文章 https ://stats.idre.ucla.edu/r/codefragments/greek_letters/

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

Taken from a very help article here https://stats.idre.ucla.edu/r/codefragments/greek_letters/

不甘平庸 2024-08-10 18:20:01

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

I just have a workaround. One may first generate an eps file, then convert it back to pgf using the tool eps2pgf. See http://www.texample.net/tikz/examples/eps2pgf/

铁憨憨 2024-08-10 18:20:01

例如,您可以使用以下内容:

title(sub=TeX(sprintf(paste("Some latex symbols are ", r'(\lambda)', "and", r'(\alpha)'))))

只需记住使用 r'()' 将 LaTeX 表达式括在 paste()
您还可以在 paste() 函数中添加命名对象。例如,

lambda_variable <- 3
title(sub=TeX(sprintf(paste(r'(\lambda=)', lambda_variable))))

不确定是否有更好的方法可以做到这一点,但上述方法对我有用:)

You can use the following, for example:

title(sub=TeX(sprintf(paste("Some latex symbols are ", r'(\lambda)', "and", r'(\alpha)'))))

Just remember to enclose LaTeX expressions in paste() using r'()'
You can also add named objects in the paste() function. E.g.,

lambda_variable <- 3
title(sub=TeX(sprintf(paste(r'(\lambda=)', lambda_variable))))

Not sure if there are better ways to do this, but the above worked for me :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文