Dear All,

I have been trying to add lines to the axis grobs of plots produced with ggplot2.

The code I have used is below. It works, although I do not think it is a really elegant way of doing what I want.... However, I am now noticing that when plotted, the width of the lines in the axis are not the same as the line widths I get for the ticks (the ticks get thicker lines). Also, when I build a function to do the same conversion, I get different (thinner) line widths for the x-axis I have been trying to find out why this is so, but I seem to have met a dead-end.

#Test
library(ggplot2)
#Set the basic overall plot options
themePublish <-list(background.fill='white', grid.fill='white', grid.colour='NA', grid.minor.colour='NA', axis.colour='black', border.colour='NA')
ggtheme(themePublish)

#Generate the data
plotdata<-data.frame(x=1:10, y=runif(10))

#Build the ggplot object

ggPlotObject<-ggplot()
ggPlotObject<-ggPlotObject+layer(data=plotdata, mapping=aes_string(x='x',y='y'),geom='point', stat='identity', size=4)
ggPlotObject<-ggPlotObject+ scale_y_continuous(limits=c(0,1), expand=c(0,0))

#################
#I define the following function
F.ggPlot.AddAxisLines<-function(ggPlotObject, col='black', lwd=2, lty='solid'){
###################################################################################################
# First, capture the ggPlot object as a gTree
ggPlotTree<-ggplot_plot(ggPlotObject)

#Get the parameters defined for the lines
LinePars <- gpar(col=col, lwd=lwd, lty=lty)

#Then, create the objects to add to the axes
YAxis.Line<-linesGrob(x=unit(c(1,1), 'npc'), y=unit(c(0,1), 'npc'), vp='left_axis', name='YAxisLine', gp=LinePars) XAxis.Line<-linesGrob(x=unit(c(0,1), 'npc'), y=unit(c(1,1), 'npc'), vp='bottom_axis', name='XAxisLine', gp=LinePars)

#Add the grobs to this object
ggPlotTreeMod<-ggPlotTree
ggPlotTreeMod<-addGrob(ggPlotTreeMod, YAxis.Line, gPath('yaxis'), grep=TRUE)
ggPlotTreeMod<-addGrob(ggPlotTreeMod, XAxis.Line, gPath('xaxis'), grep=TRUE)

#Edit the properties of the ticks, to match those of the lines
ggPlotTreeMod<-editGrob(ggPlotTreeMod, gPath('ticks'), gp=LinePars, grep=TRUE, global=TRUE)

#Output the new object

ggPlotTreeMod
}

# and then do
ggPlotTreeMod2 <- F.ggPlot.AddAxisLines(ggPlotObject)
grid.draw(ggPlotTreeMod2)

# I get different line thicknesses for the two axes

#However, if I do
ggPlotTreeMod3 <- F.ggPlot.AddAxisLines(ggPlotObject, lwd=3)
grid.draw(ggPlotTreeMod3)

# I get the same line thickness on both axes, but thicker ticks


I would really appreciate any pointer or hint.
Thanks,
Pedro

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to