【问题标题】:R: write function to set title of ggplot based on inputR:编写函数以根据输入设置ggplot的标题
【发布时间】:2015-12-08 03:21:19
【问题描述】:

我正在尝试创建一个函数,使我能够绘制一系列数据框。我正在尝试将我的绘图标题设置为一个变量,该变量将根据指示风险因素的变量而改变。

这是一个吸烟数据框和一个来自riskf的二手烟暴露数据框(原始数据框)的设置

smoking <- df.maker(subsetF$Smoking, subsetM$Smoking)
second_smoking <- df.maker(subsetF$Second.hand.smoke.exposure,      
subsetM$Second.hand.smoke.exposure


plot_function <- function(risks, riskf){

plot <- ggplot(risks, aes(provinces, value )) +  geom_bar(aes(fill = variable), 
position = "dodge", stat="identity") + scale_fill_discrete(name="Gender") + 
xlab("Provinces and Territories") + ylab("Percentage(%)") + ggtitle("") + 
theme_bw() + theme(panel.border = element_blank()) + theme(plot.title     
= element_text(size=20), axis.title.x = element_text(size=14), 
axis.title.y = element_text(size=14)) + geom_hline(yintercept=mean(risks[, 3]))

return(plot)
}


plot_function(smoking)

当我插入为风险吸烟时,我希望我的标题为“2014 年加拿大各省吸烟”,如果我为风险插入第二个吸烟,我希望标题为“2014 年加拿大各省二手烟” “等等……

【问题讨论】:

  • 你不能添加另一个参数用于标题吗? R 应该如何知道将“second_Smoking”更改为“Second Hand Smoke”?您是否打算在某个地方定义这些翻译?

标签: r function ggplot2 axis-labels


【解决方案1】:

用键添加向量:

plot_function <- function(risks){

  riskf  <- gsub("()","",sys.call()[2])
  titles <- c(smoking="Smoking by Province in Canada 2014",
              second_smoking="Second Hand Smoke by Province in Canada 2014")

  plot <- ggplot(risks, aes(provinces, value )) +  geom_bar(aes(fill = variable), 
  position = "dodge", stat="identity") + scale_fill_discrete(name="Gender") + 
  xlab("Provinces and Territories") + ylab("Percentage(%)") + 
  theme_bw() + theme(panel.border = element_blank()) +
  theme(plot.title = element_text(size=20), axis.title.x = element_text(size=14), 
  axis.title.y = element_text(size=14)) + geom_hline(yintercept=mean(risks[, 3]))+
  ggtitle(titles[riskf])

  return(plot)
}

因为我没有你的数据,所以我添加的部分是这样的:

plot_function <- function(x) {
  riskf  <- gsub("()","",sys.call()[2])
  titles <- c(smoking="Smoking by Province in Canada 2014",
              second_smoking="Second Hand Smoke by Province in Canada 2014")

  print(titles[riskf])
}

smoking <- 1:3

plot_function(smoking)
#                              smoking 
# "Smoking by Province in Canada 2014" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2018-05-19
    • 2022-01-26
    相关资源
    最近更新 更多