【问题标题】:How can I use a variable inside expression() to make the y-axis label of a bar plot in R?如何在表达式()中使用变量来制作 R 中条形图的 y 轴标签?
【发布时间】:2019-01-30 13:48:33
【问题描述】:

我想用包含一些单位的 y 轴标签制作条形图。我使用了 expression() 来正确格式化它们。如果直接在脚本中编码,则一切正常。如果我想使用变量来启用自动化,则标签显示不正确。有没有办法在 barplot() 内部或外部将变量与 expression() 一起使用?

为了使脚本自动化,我遍历了一堆文本文件并一次性创建了许多图表。要获取 y 轴标签,脚本会读取包含信息的第二个文本文件。当然,它没有按应有的格式进行格式化。因此我仍然需要使用表达式()。因此,实际的 y 轴标签文本(或其中的一部分)存储在变量中,但如果我用变量替换相应的代码段,它不会在图中显示正确的标签。

# 1) this works properly but i actually don't want to use it

    labelY <- expression(paste("Mn content [", µg,"*",mg^{-1},"DW]"))    

# 2) i want to replace "Mn content" by something else (e.g. "Fe
# content") with a variable 'varLabel' but it does not work

    labelY <- expression(paste(varLabel," [", µg,"*",mg^{-1},"DW]")) 

# 3) i tried to replace the whole label with a variable but this
# doesn't work either

    labelY <- expression(varLabel) 

# plot the graph ('dataplot' contains the actual data)

    daMightyPlot = barplot(dataplot, beside=T, legend.text=T,
        col=barColors, ylim=c(0,lim), ylab = labelY, names.arg=namesArg,
        cex.axis=1.0, cex.names = 1.0, font.lab = 1, cex.lab = 1.2
    )

如上所述,手动 y 轴标签定义确实可以正常工作。但是,当我想使用变量来替换字符串的一部分时(案例 2),它会显示其他内容作为 y 轴标签:

$(变量) [µg*mg^-1 DW]

所以它不想显示变量内容而只显示变量名。我想要的是例如:

锰含量[µg*mg^-1 DW]

...如果“Mn 含量”存储在变量中。当我用变量替换 expression() 中的整个表达式时,结果是相似的(案例 3)。

有人有解决办法吗?我错过了什么?

【问题讨论】:

    标签: r variables expression bar-chart axis-labels


    【解决方案1】:

    使用bquote:

    labelY <- expression(paste("Mn content [", µg,"*",mg^{-1},"DW]"))  
    plot.new()
    text(0.5, 0.3, labelY)
    
    varLabel <- "Fe content"
    labelY <- bquote(paste(.(varLabel)," [", µg,"*",mg^{-1},"DW]")) 
    text(0.5, 0.6, labelY)
    

    结果:

    【讨论】:

    • 顺便说一句。我会使用labelY &lt;- bquote(.(varLabel) ~ group("[", "µg"~"mg"^{-1}~DW, "]"))。它看起来更好一些。
    • 哇!非常快速的帮助。它就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多