使用“表达”使用来自数据框的值创建具有某些斜体的标签列表

发布于 2025-02-03 08:44:13 字数 1016 浏览 2 评论 0原文

我正在尝试创建一个包含斜体的标签列表。我可以用这样的“表达”来做到这一点,当我将它们放在情节上时(通过添加传说为例,但我会以不同的方式使用它们),这一切都很好。

sp.names=c(expression(paste("species ",italic("one")," sp.")),
           expression(paste("species ",italic("two")," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)

但是,我想在代码中直接指定标签中的单词,而是想从数据帧中的单元格中调用它们(因为它们有很多,并且根据我的基础数据而更改)。但是,当我尝试指定我想要的数据框单元时,它不会正确打印标签(请参见下文)。也许我想称“表达”功能可以识别的单元格有另一种方式?

df=data.frame(V1=c("species","species","species"),V2=c("one","two","three"))
sp.names=c(expression(paste(df$V1[1],italic(df$V2[1])," sp.")),
           expression(paste(df$V1[2],italic(df$V2[2])," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)

I'm trying to create a list of labels that contain italics. I can do it with "expression" like this, and when I put them on a plot (by adding a legend as an example, but I'll use them different ways), it all works nicely.

sp.names=c(expression(paste("species ",italic("one")," sp.")),
           expression(paste("species ",italic("two")," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)

enter image description here

But instead of specifying the words in the label directly in the code, I want to call them from cells in a dataframe (because there are a lot of them and they change depending on my underlying data). But when I try and specify which dataframe cell I want, it doesn't print the labels correctly (see below). Perhaps there is a different way for me to call the cell that I want that the "expression" function will recognise?

df=data.frame(V1=c("species","species","species"),V2=c("one","two","three"))
sp.names=c(expression(paste(df$V1[1],italic(df$V2[1])," sp.")),
           expression(paste(df$V1[2],italic(df$V2[2])," sp.")))
plot(1:10)
legend("topleft",legend=sp.names)

enter image description here

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

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

发布评论

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

评论(2

思念绕指尖 2025-02-10 08:44:13

使用替换,它在表达式中替换变量。

sp.names=c(substitute(V1 ~ italic(V2) ~ "sp.", df[1,]),
           substitute(V1 ~ italic(V2) ~ "sp.", df[2,]))

我还删除了不需要的粘贴(在platmath中具有不同的含义),并用代替了它,以提高可读性。

Use substitute, it substitutes variables in expressions.

sp.names=c(substitute(V1 ~ italic(V2) ~ "sp.", df[1,]),
           substitute(V1 ~ italic(V2) ~ "sp.", df[2,]))

I also removed the unneeded paste (which has a different meaning within plotmath) and replaced it with ~ for increased readability.

江挽川 2025-02-10 08:44:13

给出bquote镜头。

sp.names <- c(bquote(.(df$V1[1])~italic(.(df$V2[1]))~" sp."),
              bquote(.(df$V1[2])~italic(.(df$V2[2]))~" sp."))

plot(1:10)
legend("topleft", legend=sp.names)

Give bquote a shot.

sp.names <- c(bquote(.(df$V1[1])~italic(.(df$V2[1]))~" sp."),
              bquote(.(df$V1[2])~italic(.(df$V2[2]))~" sp."))

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