R:函数中使用的 ggplot2 未反映字体大小变量的变化

2024-05-05

我经常需要将多个不同大小的相同 ggplot2 图表输出到 png 文件。通过使用输出高度和宽度(以像素为单位)的变量,可以轻松生成每个 png 文件的大小。对于 ggplot2 部分,我使用字体大小和某些其他元素的变量,并设置一个简单的循环来在每次传递中更改这些变量。这一切都按预期工作,并且是对 R 和 ggplot2 灵活性的致敬。

大多数时候,我都会创建少数图表类型之一,其中大多数都没有变化。因此,我认为创建一个简单的函数来处理样板代码并从列表中返回 ggplot2 的绘图是有意义的。我需要做的就是将数据框、我想要在图表中使用的列的名称以及其他几个变量传递给函数。该循环为绘图创建一个名称,调用 ggplot 并将结果分配给列表中的元素。在第二遍中,它更改字体大小变量,但其他方面的行为相同。

然而,字体大小似乎没有被 ggplot 拾取。具体来说,我使用变量来控制 geom_text() 的大小、x 轴和 y 轴文本的大小以及绘图的标题。当我在从函数返回后打印列表的内容时,geom_text() 大小正如人们所期望的那样发生变化,但其他两个元素在它们应该不同时却没有变化。 (请注意,在下面的代码中,我使用两个具有相同像素大小的“中”和“大”png 文件,但通常一个文件的大小是另一个文件的两倍 - 这仅用于说明目的。)

第二张图片的标题和轴文本大小应与第一张图片不同,但事实并非如此:

因为这种方法在“内联”用作正常代码块的一部分时工作正常,所以我只能假设我调用或刷新导致问题的函数的方式存在一些简单的问题。非常感谢任何帮助。

我以前没有在 R 中使用过命名函数,而且我是一个临时程序员而不是专业人士,所以提前对下面的不可靠代码表示歉意。

# create test data
set.seed(12345)
mydf <- data.frame(passdate=seq(as.Date("1995/1/1"), by="month", length.out=204),passval=runif(204, min=25, max=100),ignoreval=runif(204, min=-21, max=-2))

myplots <- list()
myplots <- chart_high_mom(mydf,'passdate','passval','1995-02-01','2011-12-31',"My title here")

# first chart
mywidth = 700
myheight = 600
png(filename = "chart1.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[1]])
dev.off()
# second chart - this intended to be twice as large when bugs fixed
png(filename = "chart2.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[2]])
dev.off()
# end of calling code

chart_high_mom <- function(
    x = NULL, # a data frame containing the data to plot
    datecol, # name of column holding yyyy-mm-dd date series
    valcol, # name of column holding value to use for calculation
    fstartdate, # date in yyyy-mm-dd format specifying first date to plot
    fenddate, # date in yyyy-mm-dd format specifying last date to plot
    ftitle # title to add to plot
    )
    {

    require(gdata)
    require(xts)
    require(ggplot2)
    require(lubridate)    
    # strip the data frame down
    x <- subset(x,select = c(datecol,valcol))
    colnames(x) <- c('mydate','myval')
    # create year and month columns
    x$year <- as.numeric(format(as.Date(x$mydate), format="%Y"))
    x$month <- as.numeric(format(as.Date(x$mydate), format="%m"))
    # create month-on-month change column
    mydata.xts <- xts(x$myval,order.by=x$mydate)
    x$myvalmom <- diff(mydata.xts,lag=1)/lag(mydata.xts,1)

    plotlist <- list()

    for (i in 1:2) { # loop to create plot with two different sets of font sizes

        plotname <- paste("myplot", i, sep = "")

        if (i == 1) {
            fontsize <- 8
            titlesize <- 16
            geomtextsize <- 4
            ftitle <- "medium"
        }
        if (i == 2) {
            fontsize <- 24
            titlesize <- 28
            geomtextsize <- 5
            ftitle <- "large"
        }

        print(paste("i = ",i," and fontsize = ",fontsize," and plot = ",plotname,sept=""))

        plotlist[[plotname]] <- ggplot(x[x$mydate>=fstartdate & x$mydate<=fenddate,], 
            aes(x=month(mydate,label=TRUE),y=year(mydate), fill = myvalmom, label = sprintf("%1.1f%%", 100*myvalmom))) + 
          scale_y_date(major="years", format="%Y") +
          geom_tile() + 
          geom_text(data=x[x$mydate>=fstartdate & x$mydate<=fenddate,],size = geomtextsize,colour = "black") +
          scale_fill_gradient2(low = "blue", high = "red",midpoint=0) +
          scale_x_discrete(expand=c(0,0)) +
          scale_y_reverse(breaks=1980:2012, labels=1980:2012, expand=c(0,0) ) +

          opts(

          axis.text.y = theme_text(size = fontsize, colour = "grey50"),
          axis.text.x = theme_text(size = fontsize, colour = "grey50"),
          plot.title = theme_text(size = titlesize),
          title = ftitle,
          panel.grid.minor = theme_blank(),
          axis.ticks = theme_blank(),
          panel.grid.major = theme_blank(),
          axis.title.y = theme_blank(),
          axis.title.x = theme_blank(),
          panel.background = theme_rect(fill = "transparent",colour = NA),
          legend.position = "none"
          )

    }

return(plotlist)

}

首先定义绘图函数(以便它们可以接受您将要更改的参数:

chart_high_mom <- function(fontsize, titlesize, geomtextsize, ftitle,
    x = NULL, # a data frame containing the data to plot
    datecol, # name of column holding yyyy-mm-dd date series
    valcol, # name of column holding value to use for calculation
    fstartdate, # date in yyyy-mm-dd format specifying first date to plot
    fenddate # date in yyyy-mm-dd format specifying last date to plot
                         ) {


    # strip the data frame down
    x <- subset(x,select = c(datecol,valcol))
    colnames(x) <- c('mydate','myval')
    # create year and month columns
    x$year <- as.numeric(format(as.Date(x$mydate), format="%Y"))
    x$month <- as.numeric(format(as.Date(x$mydate), format="%m"))
    # create month-on-month change column
    mydata.xts <- xts(x$myval,order.by=x$mydate)
    x$myvalmom <- diff(mydata.xts,lag=1)/lag(mydata.xts,1)

    plotlist <- list()


        print(paste("i = ",i," and fontsize = ",fontsize," and titlesize = ",titlesize,sep=""))

        thisplot <- ggplot(x[x$mydate>=fstartdate &
                                             x$mydate<=fenddate,], 
            aes(x=month(mydate,label=TRUE),y=year(mydate), 
             fill = myvalmom, label = sprintf("%1.1f%%", 100*myvalmom))) + 
                    scale_y_date(major="years", format="%Y") +
                    geom_tile() + 
                    geom_text(data=x[x$mydate>=fstartdate &
                         x$mydate<=fenddate,],size = geomtextsize, 
                         colour = "black") +
          scale_fill_gradient2(low = "blue", high = "red",midpoint=0) +
          scale_x_discrete(expand=c(0,0)) +
      scale_y_reverse(breaks=1980:2012, labels=1980:2012, expand=c(0,0) ) +
          force(opts(axis.text.y = 
                  theme_text(size = force(fontsize), colour = "grey50"),
               axis.text.x = theme_text(size = force(fontsize), colour = "grey50"),
          plot.title = theme_text(size = titlesize),
          title = ftitle,
          panel.grid.minor = theme_blank(),
          axis.ticks = theme_blank(),
          panel.grid.major = theme_blank(),
          axis.title.y = theme_blank(),
          axis.title.x = theme_blank(),
          panel.background = theme_rect(fill = "transparent",colour = NA),
          legend.position = "none"
          ))
return(thisplot)

    }

....然后打电话给他们。并使用您想要的参数值调用它们:

set.seed(12345)
mydf <- data.frame(passdate=seq(as.Date("1995/1/1"), by="month", length.out=204),passval=runif(204, min=25, max=100),ignoreval=runif(204, min=-21, max=-2))

myplots <- list()

for (i in 1:2) { # loop to create plot with two different sets of font sizes
              if (i == 1) {
            print(fontsize <- 8)
            print(titlesize <- 32)
            print(geomtextsize <- 4)
            print(ftitle <- "medium");  
     myplots[[1]] <-chart_high_mom(fontsize= fontsize , titlesize= titlesize , geomtextsize= geomtextsize , ftitle= ftitle , x=mydf, 'passdate', 'passval', '1995-02-01', '2011-12-31')
      png(filename = "chart1.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[1]])
dev.off()             }
        if (i == 2) {
            fontsize <- 24
            titlesize <- 12
            geomtextsize <- 5
            ftitle <- "large"; 
     myplots[[2]] <-chart_high_mom(fontsize= fontsize , titlesize= titlesize , geomtextsize= geomtextsize , ftitle= ftitle , x=mydf, 'passdate', 'passval', '1995-02-01', '2011-12-31')
      png(filename = "chart2.png", width = 700, height = 600, units = "px", res = NA)
print(myplots[[2]])
dev.off()      }       }
# end of calling code
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R:函数中使用的 ggplot2 未反映字体大小变量的变化 的相关文章

  • 更改 pander 中的默认对齐方式 (pandoc.table)

    我目前正在切换到pander对于我的大部分时间knitr markdown格式化 因为它提供了如此出色的pandoc支持 我不太满意的一件事是默认的居中对齐 营销人员可能会喜欢它 但对于技术报告来说这是一个可怕的事情 使用的最佳选择Hmis
  • 使用 ggplot 构面时增加闪亮的绘图大小

    有没有办法增加绘图窗口的大小shiny取决于在一个中使用的面的数量ggplot图 也许使用垂直滚动 例如 使用下面的示例 当输入为 A 有三个方面 情节看起来不错 当选项 B 选择绘图数量会增加 但绘图窗口保持相同大小 导致绘图太小 是否有
  • 使用 pkg:sjPlot 函数创建一个生成部分斜体单元格的数据框

    我正在尝试创建一个简单的数据表 其中 Coral taxon 列中的属名称为斜体 而 spp 列中的属名称为斜体 属名后面的部分不大写 我尝试使用 expression 函数对 Coral taxon 的每一行进行编码 但没有成功 sum
  • R 编程常用工具

    如果已经以不同的方式问过这个问题 我深表歉意 但我找不到任何达到我想要的东西 我真的是从其他软件包 SPSS 开始接触 R 的 当我了解真正可以做什么时 我意识到我还需要其他 工具 这让我想到了我的问题 您有哪些用于开发 R 代码的设置 我
  • R中整数类和数字类有什么区别

    我想先说我是一个绝对的编程初学者 所以请原谅这个问题是多么基本 我试图更好地理解 R 中的 原子 类 也许这适用于一般编程中的类 我理解字符 逻辑和复杂数据类之间的区别 但我正在努力寻找数字类和整数类之间的根本区别 假设我有一个简单的向量x
  • 在 igraph 中为社区分配颜色

    我在 igraph 中使用 fastgreedy community 检测算法在 R 中生成社区 代码返回 12 个社区 但是在绘图时很难识别它们 因为它返回的图的颜色数量有限 我怎样才能用十二种不同的颜色绘制这个图表 l2 lt layo
  • 如何在 R 中将字符串解析为层次结构或树

    有没有办法将表示组的字符串解析为 R 中的层次结构 假设我的小组结构如下 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 3 1 1 3 1 1 1 3 2 1 1 3 3 1 2 1 2 1 1 2 1 1 1 2 1 2 1
  • 如何定义“f_n-chi-square”函数并使用“uniroot”求置信区间?

    I want to get a 95 confidence interval for the following question 我已经写了函数f n在我的 R 代码中 我首先使用 Normal 随机采样 100 个样本 然后定义函数h
  • 按特定样本前缀对列名称向量进行子集化

    假设我有一个如下所示的数据框 ca01 lt c 1 10 ca02 lt c 2 11 ca03 lt c 3 12 stuff 1 lt rep test 10 other lt rep 9 10 data lt data frame
  • R- 将某些列从 0 标准化为 1,其值等于 0

    我最近开始使用 are 我想扩展我的数据矩阵 我在这里找到了一种方法在两点之间缩放系列 https stackoverflow com questions 5468280 scale a series between two points
  • ubuntu中R的igraph包的安装

    我使用以下命令在 ubuntu 中安装 R 的 igraph 包 install packages igraph 但我收到一条错误消息 警告 无法访问存储库的索引 http ftp iitm ac in cran src contrib h
  • 删除字符串末尾的句点和数字

    如何删除尾随句点 后面紧跟一个数字 长度为一位或两位数字 例子 z lt c awe p 56 red 45 ted 5 you 88 tom 我只想删除 45和 5 你只需要一个简单的正则表达式 z new gsub 0 9 z 一些评论
  • 如何使用 R 将每个文件的数据添加为附加行,从而将不同的 .csv 文件合并为一个完整的文件?

    我有几个不同的文件夹 它们都包含一个 csv 文件 所有这些 csv 文件都有一个单独的列 其中包含实验的一种条件的数据 我想以将每个文件的数据添加为新列的方式合并这些 csv 文件 目前 它看起来像这样 C1 csv 102 106 15
  • randomForest 包在删除一个预测类时的奇怪行为

    我正在运行一个随机森林模型 它产生的结果从统计角度来看对我来说完全没有意义 因此我确信有些东西mustrandomForest 包的代码出现错误 至少在模型的本次迭代中 预测 左侧变量是具有 3 种可能结果的政党 ID 民主党 独立党 共和
  • rpart“as.character(x) 中的错误:无法强制类型 'builtin' 为类型 'character' 的向量”消息是什么意思?

    我一直在用头撞rpart几天了 尝试为我拥有的这个数据集制作分类树 我认为现在是时候询问生命线了 我确信这是我没有看到的愚蠢的事情 但这里是我一直在做什么 EuropeWater lt read csv file paste Users a
  • R、Rcpp 与 Armadillo 中矩阵 rowSums() 与 colSums() 的效率

    背景 来自 R 编程 我正在扩展到 C C 形式的编译代码Rcpp 作为循环交换 以及一般的 C C 效果的实践练习 我实现了 R 的等效项rowSums and colSums 矩阵的函数Rcpp 我知道它们以 Rcpp 糖的形式存在 并
  • R中的字典数据结构

    在 R 中 我有 例如 gt foo lt list a 1 b 2 c 3 如果我输入foo I get a 1 1 b 1 2 c 1 3 我怎样才能看透foo仅获取 键 列表 在这种情况下 a b c R 列表可以具有命名元素 因此可
  • R - 计算 bin 中特定值的数量

    我有一个如下所示的数据框 df Value lt c 1 1 0 2 1 3 4 0 0 1 2 0 3 0 4 5 2 3 0 6 Sl lt c 1 20 df lt data frame Sl Value gt df Sl Value
  • 警告消息 - 来自 dummies 包的 dummy

    我正在使用 dummies 包为分类变量生成虚拟变量 其中一些变量具有两个以上类别 testdf lt data frame A as factor c 1 2 2 3 3 1 B c A B A B C C C c D D E D D E
  • 需要在R中按行绑定列表数据

    我在 R 中按行绑定列表时遇到问题 我的列表数据集是 id 1 data k 1 id k b c 1 1 1 3 data k 2 id k b c 1 2 1 4 id 2 data k 1 id k b c 2 1 1 6 data

随机推荐