【问题标题】:Add simultaneously a character and a string on ylab in ggplot在ggplot中的ylab上同时添加一个字符和一个字符串
【发布时间】:2020-10-27 10:57:07
【问题描述】:

我有一个 23 df 的列表 plotDat,我正在使用 ggplotlapply 和一个匿名函数为每个数据框创建和导出图表。对于每个 df,图表表示浓度列(Y 轴)与年份列(X 轴)。

pdf("Plots.pdf")
lapply(names(plotDat), function(i){
  ggplot(plotDat[[i]], aes(Year, Concentration, group = Chemicals, col = Chemicals)) +
    geom_line() +
    geom_point() +
    ggtitle(paste("", i)) +
    scale_x_continuous(breaks = round(seq(min(Data_total$Year), max(Data_total$Year), by = 1),1)) +
    xlab("Year") +
    ylab("Concentration in (Mol/L or Mol/Kg)") 
})
dev.off()

问题在于,根据 df,浓度以两种不同的单位(摩尔/升和摩尔/千克)给出。每个 df 都有一个名为 Unit 的列,其中包含 Mol/L 或 Mol/Kg。现在,我添加了ggplot ... ylab("Concentration in (Mol/L or Mol/Kg)"),但这并不严格,我希望为每个地块在ylab 中获得正确的单位。

我的问题是:是否可以在ylab 中添加一个字符串“concentration in” 和在ggplot 中表示plotDat$Unit[[i]] 的字符?

ylab(plotDat$Unit[i]) 实际上没有工作

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    假设 Unit 列会有很多行具有相同的值,我们只需要获取其中之一,[ 1 ]:

    ylab(paste("Concentration in", plotDat[[ i ]]$Unit[ 1 ]))
    

    或者我们可以使用独特的

    ylab(paste("Concentration in", unique(plotDat[[ i ]]$Unit)))
    

    可重现的例子:

    library(ggplot2)
    
    plotDat <- split(iris, iris$Species)
    
    res <- lapply(names(plotDat), function(i){
      ggplot(plotDat[[ i ]], aes(Sepal.Length, Sepal.Width)) +
        geom_point() +
        ylab(paste("Concentration in", plotDat[[ i ]]$Species[ 1 ]))
      })
    
    res[[ 1 ]]
    

    【讨论】:

    • 感谢您的帮助,它完美运行!但我不太明白为什么需要在“Unit [1]”中添加“[1]”
    • @Sylvain 因为 Unit 列会有很多行,我们只需要获取其中之一。我假设在数据框单元列中,每一行都重复相同的值。
    • 是的,每个df只有一个$Unit字符。而且case有2个不同的字符,请问你这种情况怎么处理?
    • @Sylvain 我会说基于多数将所有转换为数据框中的同一单位?但是您最好将此新要求作为新问题发布。如果您有 10 个 Mol/L 值和 10 个 Mol/Kg 值,您如何决定使用哪一个?
    • 你是对的,这不是绘图和图形的问题,而是如何处理 df 中的不同数据。无论如何,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2011-04-22
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多