R:函数中使用的ggplot2不反映字体大小变量的变化 [英] R: ggplot2 used in function not reflecting change in font size variable

查看:141
本文介绍了R:函数中使用的ggplot2不反映字体大小变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常需要几个不同大小的相同ggplot2图表输出到png文件。每个PNG文件的大小很容易通过使用像素输出高度和宽度的变量生成。对于ggplot2部分,我使用了字体大小和某些其他元素的变量,并设置了一个简单的循环来更改每遍中的变量。这一切都按预期工作,并且是对R和ggplot2灵活性的致敬。



大多数时候我创建少量图表类型之一,大多数这不会有所不同。因此,我认为创建一个简单的函数来查看样板代码并从列表中返回ggplot2的图是有意义的。我所需要做的就是传递函数的数据框,我想在图表中使用的列的名称和一些其他变量。循环为该图创建一个名称,调用ggplot并将结果赋给列表中的一个元素。第二遍它改变字体大小的变量,但其他行为相同。



然而,字体大小似乎没有被ggplot拾起。具体来说,我使用变量来控制geom_text()的大小,x和y轴文本的大小以及图的标题。当我从函数返回列表后打印列表的内容时,geom_text()的大小正在发生变化,但其他两个元素在应该不同时保持不变。 (请注意,在下面的代码中,我使用了两个相同像素大小的'medium'和'large'png文件,但通常其中一个会比另一个大两倍 - 这仅仅是为了说明目的。)





而第二张图片应该有不同的标题和轴文字大小,但不包括: .stack.imgur.com / V75wz.pngalt =Image 2>



因为这种方法在使用'in-line'作为正常代码块我只能假设我的调用方式存在一些直接的问题,或者可能会刷新导致问题的函数。任何帮助我们都非常感谢。



我之前没有在R中使用过命名函数,而且我是一个休闲程序员而不是专业人员,所以对于下面这些狡猾的代码, 。

 #创建测试数据
set.seed(12345)
mydf< - data.frame (passdate = runif(204,min = 25,max = 100),ignoreval = runif(passdate = seq(as.Date(1995/1/1),by =month,length.out = 204) 204,min = -21,max = -2))

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

#第一张图
mywidth = 700
myheight = 600
png (文件名=chart1.png,width = 700,height = 600,units =px,res = NA)
print(myplots [[1]])
dev.off()
#秒图 - 当错误修正时,这个数字应该是两倍大
png(filename =chart2.png,width = 700,height = 600,units =px,res = NA)
print(myplots [[2]])
dev.off()
#调用代码结束

chart_high_mom < - 函数(
x = NULL,#包含要绘制数据的数据框
datecol,#保存yyyy-mm-dd日期系列的列的名称
valcol,#用于计算的列持有值的名称
fstartdate,#以yyyy-mm-dd格式指定第一个日期的格式
fenddate,#以yyyy-mm-dd格式指定最后日期以绘制$













$ $ b require(lubridate)
#删除数据帧
x< - subset(x,select = c(datecol,valcol))
colnames(x)< -c(' (格式(as.Date(x $ mydate),format =%Y))$($ m $' b $ bx $ month < - as.numeric(格式(as.Date(x $ mydate),format =%m))
#创建月份更改列
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){#循环创建两种不同字体大小的情节

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,color =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,color =grey50),
axis.text.x = theme_text(size = fontsize,color =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,color = NA),
legend .position =none


}

return(plotlist)

}

>

  chart_high_mom<  -  function(fontsize,titlesize,geomtextsize,ftitle,
x = NULL,#data frame contains data to plot
datecol,#保存yyyy-mm-dd日期系列的列名
valcol,#用于计算的列持有值名称
fstartdate,#日期格式为yyyy-mm-dd格式指定第一个日期以绘制
fenddate#日期,格式为yyyy-mm-dd,指定最后一个日期以绘制
){


#删除数据帧
x< - subset(x, select = c(datecol,valcol))
colnames(x)< - c('mydate','myval')
#创建年份和月份列
x $ year< - as .nu​​meric(format(as.Date(x $ mydate),format =%Y))
x $ month < - as.numeric(format(as.Date(x $ mydate),format =% m))
#创建月份更改列
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,和fontsize =,fontsize和titlesize =,titlesize,sep =))

thisplot< - ggplot(x [x $ mydate> = fstartdate&
x $ mydate< = fenddate,],
aes(x = month(mydate,label = TRUE),y = year(mydate),$ b $ fill = myvalmom,label = sprintf( (%=year,format =%Y)+
geom_tile()+
geom_text(data = x [x $ mydate> = fstartdate&
x $ mydate< = fenddate,],size = geomtextsize,
color =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),color =grey50),
axis.text.x = theme_text(size = force(fontsize),color =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,color = NA),
legend.position =none
))
return(thisplot)

}

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

pre $ $ $ $ $ $ $ $ $ $ $ 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如果(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 < - 大;
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()}}
#调用代码结束


I frequently need several different sizes of the same ggplot2 chart output to png files. The size of each png file is easy enough to generate by using variables for the output height and width in pixels. For the ggplot2 part I use variables for the size of fonts and certain other elements and set up a simple loop that changes those variables in each pass. This all works as expected and is a tribute to the flexibility of R and ggplot2.

Most of the time I am creating one of a small number of chart types, most of which do not vary. Accordingly I thought it would make sense to create a simple function that looks after the boilerplate code and returns the plots from ggplot2 in a list. All I need to do is pass to the function the data frame, the name of the column I want used in the chart and a couple of other variables. The loop creates a name for the plot, calls ggplot and assigns the result to an element in the list. On the second pass it changes the font size variables but otherwise behaves identically.

However, the font sizes do not seem to be getting picked up by ggplot. Specifically, I am using variables to control the size of geom_text(), the size of the x and y axis text and the title of the plot. When I print the contents of the list after it is returned from the function, the geom_text() size is changing as one would expect, but the other two elements are unchanged when they should be different. (Note that in the code below I am using two 'medium' and 'large' png files with the same pixel size but usually one would be twice as large as the other - this is just for illustrative purposes.)

And the second image, which should have different title and axis text sizes to the first, but does not:

Because this approach works fine when used 'in-line' as part of a normal code chunk I can only assume that there is some straightforward problem with the way I am calling or perhaps refreshing the function that is causing the problem. Any help much appreciated.

I haven't used named functions in R before and I am a casual programmer rather than a professional, so apologies in advance for the dodgy code below.

# 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)

}

解决方案

Define your plot functions first (so they can accept the parameters you will be changing:

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)

    }

.... then call them. And call them with the parameter values you want:

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

这篇关于R:函数中使用的ggplot2不反映字体大小变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆