1

I think I am having an issue regarding variable scope but can't figure out how to work around it. Essentially I create a data frame in an R function and then use ggplot to call variables out of that data frame. I keep getting an error stating that the object dataframe was not found.

library("ggplot2")
library("reshape2")
library("RColorBrewer")


singleColor <- brewer.pal(8, "Dark2")[1]
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", 
"#F0E442", "#0072B2", "#D55E00", "#CC79A7")

set.seed(42) ## for the differents sample call
posRespt <- data.frame(Section = rep(1, 11),
                      Order = 1:11,
                      Question = LETTERS[1:11],
                      Response = rep('Very Important', 11),
                      Males = sample(1:40, 11, replace = TRUE),
                      Females = sample(1:40, 11, replace = TRUE))
posRespt$Total <- with(posRespt, Males + Females)



BannerDemoPlots <- function(titleText, fname, yLabel, xLabel, DemColumns){
  temp <- subset(posRespt, select=c(1:3, DemColumns))  
  tempDemoDF <- melt(temp, id=c("Section","Order", "Question"))
  tempDemoDF <- tempDemoDF[order(tempDemoDF$Order, tempDemoDF$variable),]
  #  print(tempDemoDF)

  DemoPlots <- ggplot(data=tempDemoDF, aes(Question, value, group=variable, fill=cbPalette)) + geom_bar(stat="identity", aes(fill=variable), position="dodge") + coord_flip() + ylim(0, 100) 
  DemoTheme <- labs(title= titleText, x=xLabel, y=yLabel)
  AxisColors <- theme(axis.text.x = element_text(colour = "black"), axis.text.y = element_text(colour = "black"))
  BarValues <- geom_text(aes(data=tempDemoDF, y=variable, label = value), position = position_dodge(width=1))
  Colors <- scale_fill_manual(values=cbPalette)

  DemoPlot <- DemoPlots + DemoTheme + AxisColors + Colors + BarValues
  DemoPlot
  ggsave(filename=fname, plot=(DemoPlot), width=6.5, height=8.5, units='in', dpi=300)
  return(tempDemoDF)
}

BannerDemoPlots(titleText="Gender", xLabel='', yLabel="Percent Responding 'Very Important'", fname="/home/huntdj/Army STARRS/Programs/Banner Data Charts/EnlistmentGender.eps", DemColumns=c(6:7))

The ERROR I get states:

Error in eval(expr, envir, enclos) : object 'tempDemoDF' not found

Any help would be greatly appreciated!

bdemarest
  • 14,397
  • 3
  • 53
  • 56
Devin Hunt
  • 25
  • 4
  • I should add that this is pointing to the BarValues line of code. the ggplot seems to work otherwise. I suppose it isn't ggplot that is the issue, but the geom_text function that is a problem. – Devin Hunt Jan 10 '14 at 16:25
  • In your call to `geom_text(...)` you have `tempDemoDF` in the `aes(...)` call. Try `geom_text(data=tempDemoDF, aes(y=variable,...))` – jlhoward Jan 10 '14 at 16:27
  • Thanks, but that doesn't seem to fix the issue. I still have the same error message. – Devin Hunt Jan 10 '14 at 16:34
  • Why the `detach` call I don't see any `attach` ? – dickoa Jan 10 '14 at 16:39
  • Sorry, that detach shouldn't be there. I had tried to attach the dataframe, but that didn't work. This still doesn't resolve it. – Devin Hunt Jan 10 '14 at 16:41
  • 2
    Try to create a smaller reproductible example with the same error. We don't have access to your data so is really difficult to help here – dickoa Jan 10 '14 at 16:44
  • Where's your *tempDemoDF* variable? – Fernando Jan 10 '14 at 16:46
  • See [making reproducible examples](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – BrodieG Jan 10 '14 at 16:47
  • Could please edit your post and add the code you just wrote in your last comment. – dickoa Jan 10 '14 at 17:02
  • @dickoa It won't matter. There are numerous discrepancies between that data and what the function expects. There is no Order column. The data frame name is (was) spelled wrong. And even if you fixed that, we wouldn't know how exactly to call the function. What should fname be? What should DemColumns be? – joran Jan 10 '14 at 17:04
  • **You can edit your questions!** If you need to add something **to your question** _do that_! – joran Jan 10 '14 at 17:07
  • Surprise! `cbPallete` isn't something you gave us. I'm moving on now...good luck! – joran Jan 10 '14 at 17:10
  • I've updated the question to include this new text – Devin Hunt Jan 10 '14 at 17:12
  • The code is now creating a reproducible example. Thank you dickoa for the help – Devin Hunt Jan 10 '14 at 17:36
  • I'm finding that if I comment off the `+ BarValues` in the Demoplot statement it works fine. – Devin Hunt Jan 10 '14 at 17:40
  • 1
    The syntax you use for `geom_text` is not the right one. Two things to correct, first : you put the `data` parameter inside `aes` it has to be outside and you have to provide an `x` into `aes` (and don't forget that you flipped your coord). I think that if you can correct these two errors, everything will work fine http://docs.ggplot2.org/current/geom_text.html – dickoa Jan 10 '14 at 17:44
  • Try aes_string instead of aes. Check out the documentation for this. – marbel Jan 10 '14 at 17:59
  • After moving the data statement I get an `Error: Discrete value supplied to continuous scale` – Devin Hunt Jan 10 '14 at 18:05

1 Answers1

1

I got this to work but had to make many changes:

  1. as many pointed out, you had tempDemoDF inside the aes call for geom_text
  2. additionally, you were trying to plot your question as the y value which doesn't work because y (though looks like x here because it's flipped) is supposed to be continuous
  3. You were trying use variable as y value for your text, which doesn't make any sense; instead I used the value for the y value of your text.
  4. Are you trying to color by variable or by question? Your color scheme suggest the latter, but your code does the former (I left it as is).

There likely were other issues that I fixed as well but don't recall.

enter image description here

library("ggplot2") library("reshape2") library("RColorBrewer")

singleColor <- brewer.pal(8, "Dark2")[1]
cbPalette <- c("#999999", "#E69F00", "#56B4E9", "#009E73", 
               "#F0E442", "#0072B2", "#D55E00", "#CC79A7", "red", "green", "blue")

set.seed(42) ## for the differents sample call
posRespt <- data.frame(Section = rep(1, 11),
                       Order = 1:11,
                       Question = LETTERS[1:11],
                       Response = rep('Very Important', 11),
                       Males = sample(1:40, 11, replace = TRUE),
                       Females = sample(1:40, 11, replace = TRUE))
posRespt$Total <- with(posRespt, Males + Females)

BannerDemoPlots <- function(
  titleText, fname, yLabel, xLabel, DemColumns){
  temp <- subset(posRespt, select=c(1:3, DemColumns))  
  tempDemoDF <- melt(temp, id=c("Section","Order", "Question"))
  tempDemoDF <- tempDemoDF[order(tempDemoDF$Order, tempDemoDF$variable),]

  DemoPlots <- ggplot(
    data=tempDemoDF,
    aes(x=Question, y=value, group=variable)) + 
    geom_bar(stat="identity", aes(fill=variable), position="dodge") + 
    coord_flip() + ylim(0, 100)
  DemoTheme <- labs(title= titleText, x=xLabel, y=yLabel)
  AxisColors <- theme(axis.text.x = element_text(colour = "black"), axis.text.y = element_text(colour = "black"))
  BarValues <- geom_text(
    data=tempDemoDF, 
    aes(label = value, y=value), 
    position = position_dodge(width=1)
  )
  Colors <- scale_fill_manual(values=cbPalette)

  DemoPlot <- DemoPlots + DemoTheme + AxisColors + Colors + BarValues
  #ggsave(filename=fname, plot=(DemoPlot), width=6.5, height=8.5, units='in', dpi=300)
  print(DemoPlot)
  return(tempDemoDF)
}

BannerDemoPlots(
  titleText="Gender", xLabel='', 
  yLabel="Percent Responding 'Very Important'", 
  fname="test.eps", DemColumns=c(6:7))
BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • I'd really like the Male and Female on the same plot grouped together, which I had except for the labels – Devin Hunt Jan 10 '14 at 18:09
  • Ah, I think I solved the problem. I changed in my original code the Barvalues to read `BarValues <- geom_text(data=tempDemoDF, aes(label=value), position = position_dodge(width=1))` – Devin Hunt Jan 10 '14 at 18:14
  • @DevinHunt, They are listed at the top of my answer. Primarily you were trying to plot your y variables on your x axes and vice versa. `coord_flip` can be confusing. If this works for you please mark question as answered (and upvote if you're particularly sastisfied). – BrodieG Jan 10 '14 at 18:17