如何在R中的ggplot2函数中调整geom_text()

时间:2013-09-05 03:25:52

标签: r function ggplot2

我正在使用自定义函数“stepPlot”创建一个步骤图,该函数正常工作。当我试图在这个函数中放置一个geom_text()时,我陷入了困境。有趣的是,当geom_text()不在函数中时,它会起作用。任何人都可以帮我调整geom_text()。有两部分:(1)“labelPosiX”是标签文本的水平位置,(2)geom_text()位于函数的末尾。 “labelPosiY”,标签的垂直位置,将用数字手动指定。这两行代码已被停用。提前致谢

stepPlot <- function(Data,xVar, yVar, LegendTitle="", GroupLabels, Plottitle="",labelPosiY, labelText="A"
                     # plot specifications remain the same over data subsets. Ignore these setting when calling the function  
                     GroupColour=c("black","blue","orange"), LineTypeGroup=c("solid","solid","solid"), LineSize=1,
                     LegendPosition=c(0.5,0.8),
                     YaxisTitle="", YAxisTitleSize=element_blank(),
                     XAxisText=element_text(size=20),AxisTextSize=15,LegendTitleSize=10, LegendTextSize=10,LegendKeySize=10,
                     PlotTitleSize=15
                      ){
# define x limits (Xmin, Xmax), x break increments (BreakIncreX),level of breaks (GroupBreaks),horizontal position of label text (labelPosiX)
  Xmin <- min(Data[xVar])-1 
  Xmax <- max(Data[xVar])+1
  BreakIncreX <- round((Xmax-Xmin)/6)
  GroupBreaks <-unique(Data$trt_label) 
  #labelPosiX <-min(Data[xVar])+2

# define y maximal limit (limitYMax),y break increments (BreakIncreY)   
  library(plyr)
  limitYMax <- round_any(max(Data[yVar]), 100, f = ceiling)
  BreakIncreY <- round_any(max(Data[yVar])/5, 100, f = ceiling)


# step plot  
  ggplot(Data, aes_string(x=xVar, y=yVar, group='trt_label'))+
  geom_step(aes(colour=trt_label, linetype=trt_label), direction='hv',size= LineSize)+ #specify step curve from different group with colours, colour by default
  scale_y_continuous(YaxisTitle, limits=c(0,limitYMax), expand=c(0,0), breaks=seq(0,limitYMax,by=BreakIncreY))+
  scale_x_continuous("Age of adults in days", limits=c(Xmin, Xmax), expand=c(0,0), breaks=seq(Xmin,Xmax,by=BreakIncreX)) +
  scale_colour_manual(name=LegendTitle,
                                    breaks=GroupBreaks,
                                    labels=GroupLabels,
                                    values=GroupColour
                      )+  # change default colours to manually specified grey scale
  scale_linetype_manual(name  =LegendTitle,
                        breaks=GroupBreaks,
                        labels=GroupLabels,
                        values=LineTypeGroup
                        )+    
  guides(colour = guide_legend(LegendTitle), linetype = guide_legend(LegendTitle))+ # merge two legends into a single one                                           
  theme_bw() +   # maek background theme black and white                   
  theme(axis.title.x = element_blank(), #font size of x axis title
        axis.title.y = YAxisTitleSize, #font size of y axis title
        axis.text.x  = XAxisText,                              #font size of x axis text 
        axis.text.y  = element_text(size=AxisTextSize),                              #font size of y axis text  
        legend.position=LegendPosition,
        legend.title=element_text(size=LegendTitleSize),                                #font size of legend title
        legend.text = element_text(colour="black", size = LegendTextSize, face = "bold"), #font size of legend text
        legend.key.size=unit(LegendKeySize,'points'), ## ben - added to shrink the legend 
        legend.background=element_blank(), ## ben - added to get rid of white background
        panel.grid.major = element_line(size = 0.5, colour = '#FFFFFF'),
        panel.grid.minor = element_line(colour = NA), # colour = NA to suppress gridlines, reappear if colour='black'
        plot.title=element_text( face="bold", size=PlotTitleSize) # aduust plot title size
        )+
  ggtitle(Plottitle)

  # add label text
  **#+ geom_text(aes(labelPosiX, labelPosiY, label="test"), colour="black",size=5)**                                   }
                                         }

我添加文本的旧方法有效,但我希望将geom_text移动到函数中。

source("C:/Now/R/Rfunction_stepPlot.R")
fig17b <-stepPlot(Data=df17b,xVar= "age", yVar='mean_cumSumDurLeftByBeeAge', 
LegendTitle="Precocious topical",GroupLabels=c("acetone", "untreated", "methoprene"),
Plottitle="weighed hive"
)+
geom_text(aes((min(df17b$age)+2), 3700, label="A"), colour="black",size=5)

1 个答案:

答案 0 :(得分:1)

以下是将geom_text的{​​x,y}位置传递给函数的一种方法:

通常,将其作为ggplot正在绘制的数据框的一部分。 (使用SimonO101的建议,这是mtcars的工作原理。)

plotFunction <- function (df, labelPosiY) {
  df$xPos = df$cyl #add columns to the data frame
  df$yPos = labelPosiY 
  p <- ggplot(data=df, aes(x=cyl, y=mpg)) + geom_step(aes(colour=gear, direction='hv',size=2))
  p <- p + geom_text(aes(xPos, y=yPos, label="test"), colour="black",size=5)
  return (p)
}

现在,请致电

plotFunction(mtcars, 17)

产生

enter image description here

您可以尝试让代码的geom_text部分工作,然后引入图表的所有其他方面。