2

Possible Duplicate:
add “floating” axis labels in facet_wrap plot

DataLink: https://www.dropbox.com/s/q45t9hng4mryi6y/GTAP_CCShocks2.csv

Code:

   # Loading the data
   climshocks <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_CCShocks2.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)

   # Data manipulations
   ccshocks <- as.data.frame(climshocks)
   ccshocks[4:4] <- sapply(ccshocks[4:4],as.numeric)
   ccshocks <- droplevels(ccshocks)
   ccshocks <- transform(ccshocks,region=factor(region,levels=unique(region)))

   library(reshape)
   library(ggplot2)
   library(grid)

   #--------------------------------------------------------------------------------
   #### Average of climate-induced yield percent change for all regions by crop
   #--------------------------------------------------------------------------------

   #_Code_Begin...
   Avgccshocks.f <- melt(ccshocks)
   Avgccshocks.f <- Avgccshocks.f[Avgccshocks.f$sres %in% c("AVERAGE"), ]

   PlotAvgccshocks <- ggplot(data = Avgccshocks.f, aes(factor(region), value))
   PlotAvgccshocks + geom_bar(stat="identity") + 
   theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 14, hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) + 
   ylab("Yield(%change)") + theme(axis.text.y = element_text(colour = 'black', size = 14, hjust = 0.5, vjust = 0.5), axis.title.y = element_text(size = 14, hjust = 0.5, vjust = 0.5, face = 'bold')) + 
   theme(strip.text.x = element_text(size = 16, hjust = 0.5, vjust = 0.5, face = 'bold')) +
   facet_wrap(~crops, scales="free_y", ncol=3)
   ggsave("PlotAvgccshocks.png")

   #_Code_End...

Result: Resulting plot

My Question: Is there a way in ggplot to add the labels to the x-axis under the two last columns. I know I could do so by replacing "free_y" with "free" in facet_wrap(), but that would add the labels to all panels in the plot, which would make it eye-unfriendly.

What I am looking for is either add the labels right underneath the two remaining columns, or add it two sets of x-axis labels but at the same level with the labels of the "wht" panel.

I hope my question was clear.

Thanks in advance.

P.S: I have tried to use a function created by Julius in response to add “floating” axis labels in facet_wrap plotto solve the problem and the code is below

    #7- Function to add x-axis labels to all plots using facet_wrap()
    #----------------------------------------------------------------

    library(grid)
    # pos - where to add new labels
    # newpage, vp - see ?print.ggplot
    facetAdjust <- function(x, pos = c("up", "down"), 
                    newpage = is.null(vp), vp = NULL)
    {
    # part of print.ggplot
    ggplot2:::set_last_plot(x)
    if(newpage)
    grid.newpage()
    pos <- match.arg(pos)
    p <- ggplot_build(x)
    gtable <- ggplot_gtable(p)

    # finding dimensions
    dims <- apply(p$panel$layout[2:3], 2, max)
    nrow <- dims[1]
    ncol <- dims[2]

    # number of panels in the plot
    panels <- sum(grepl("panel", names(gtable$grobs)))
    space <- ncol * nrow

    # missing panels
    n <- space - panels

    # checking whether modifications are needed
    if(panels != space){

    # indices of panels to fix
    idx <- (space - ncol - n + 1):(space - ncol)

    # copying x-axis of the last existing panel to the chosen panels  
    # in the row above

    gtable$grobs[paste0("axis_b",idx)] <- list(gtable$grobs[[paste0("axis_b",panels)]])
    if(pos == "down"){
    if pos == down then shifting labels down to the same level as 
    # the x-axis of last panel
    rows <- grep(paste0("axis_b\\-[", idx[1], "-", idx[n], "]"), 
               gtable$layout$name)
    lastAxis <- grep(paste0("axis_b\\-", panels), gtable$layout$name)
    gtable$layout[rows, c("t","b")] <- gtable$layout[lastAxis, c("t")]}}

    # again part of print.ggplot, plotting adjusted version
    if(is.null(vp)){
    grid.draw(gtable)}
    else{
    if (is.character(vp)) 
    seekViewport(vp)
    else pushViewport(vp)
    grid.draw(gtable)
    upViewport()}
    invisible(p)}

So, basically i run this code for the "facetAdjust()" function and call it for my plot "PlotAvgccshocks", but an error message pops up and is as follows:

ErrorMessage:

facetAdjust(PlotAvgccshocks) Error: No layers in plot

Any thoughts?

Thanks again

Community
  • 1
  • 1
iouraich
  • 2,944
  • 5
  • 29
  • 40
  • I udpated the question by adding a code produced by Julius to solve the issue at hand, nonetheless as I mention above, running it produced an error message that described previously. – iouraich Jan 25 '13 at 21:52
  • 1
    The problem is that you use `facetAdjust(PlotAvgccshocks)` where `PlotAvgccshocks` is only `ggplot(...)`. That is, without `+geom_bar(...)` etc. – Julius Vainora Jan 26 '13 at 12:40
  • Thanks for the clarification. It is working fine now. Just one more thing, I try to save the plot using the command ggsave("PlotAvgccshocks.png"), and it does save the file but with the x-axis not showing up. Any clue to why is that happening? – iouraich Jan 26 '13 at 19:50
  • 1
    In that case the problem is that `facetAdjust` takes a ggplot2 object as an input (`ggsave` too) but returns a gtable. So I would offer to use `pdf(filename = "PlotAvgccshocks.png");facetAdjust(PlotAvgccshocks);dev.off()` – Julius Vainora Jan 27 '13 at 13:04

0 Answers0