Sturm
Sturm

Reputation: 13

ggplot graph stored erase each others

Here is some code which reproduces my issue:

x <- as.factor(1:20)
y <- 1:20
id <- as.factor(c(rep(0,19),1))
g1 <- ggplot() + geom_bar(stat = "identity", aes(x = x, y = y, color = id, fill = id), width = 0.5) + ggtitle("g1")
g1 # First print

y <- 20:1
g2 <- ggplot() + geom_bar(stat = "identity", aes(x = x, y = y, color = id, fill = id), width = 0.5) + ggtitle("g2")
g2
g1 # Second print

As you can see when running the code above, the first time you print g1, you have a barplot starting at (factor 1, y = 1), ending at (factor 20, y = 20). After having created g2, if you print again g1, it looks the same than g2, except the title which isn't modified.

I'm really puzzled, any help would be much appreciated !

Upvotes: 1

Views: 28

Answers (1)

MrFlick
MrFlick

Reputation: 206197

ggplot works best when you pull data from a data.frame rather than the global environment. If you did

x <- as.factor(1:20)
y <- 1:20
id <- as.factor(c(rep(0,19),1))
g1 <- ggplot(data.frame(x, y, id)) + 
  geom_bar(stat = "identity", aes(x = x, y = y, color = id, fill = id), width = 0.5) + 
  ggtitle("g1")  
y <- 20:1
g2 <- ggplot(data.frame(x, y, id)) + 
   geom_bar(stat = "identity", aes(x = x, y = y, color = id, fill = id), width = 0.5) + 
   ggtitle("g2")

everything would work fine.

The "problem" is that ggplot doesn't actually "build" the plot until you print it. And when you are linking to variable names with aes(), it just tracks the variable name, not the value. So it uses whatever the current value is when the plot prints. When we "trap" data inside a data.frame, we are capturing the current value of the variable so that we can use that later.

Upvotes: 2

Related Questions