Question

I'm trying to use ggplot2 to draw a histogram that has different colour-bars for different intervals of x.

After referring to Hadley's solution in: how to define fill colours in ggplot histogram?, I arrived at the following:

library(ggplot2)

set.seed(1)
a <- seq(from=1, to=10000)
b <- rnorm(10000)
c <- data.frame(a,b) # Convert to DF

ggplot(c, aes(x=b, fill=cut(..x.., breaks=c(-2, -1, -0.5, 0, 0.5, 1, 2)))) +
  geom_histogram(binwidth=0.1, color="steelblue")

However, when I try to define the break points into a variable, MyBreaks, to be passed into aes(), I get an error: "Error in cut.default(x, breaks = MyBreaks) : object 'MyBreaks' not found."

My code that generated the error:

MyBreaks <- c(-2, -1, -0.5, 0, 0.5, 1, 2)
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks))) +
  geom_histogram(binwidth=0.1, color="steelblue")

I did some research on similar errors encountered by other users, but the solutions did not seem to work for me.

For instance, the solution in How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.) gave: "Error: Aesthetics must either be length one, or the same length as the dataProblems:MyBreaks". My code is:

ggplot(c, aes(x=b, MyBreaks1=MyBreaks, fill=cut(..x.., breaks=MyBreaks1))) +
  geom_histogram(binwidth=0.1, color="steelblue")

I then tried the solution in Local Variables Within aes but this gave the same: "Error in cut.default(x, breaks = MyBreaks) : object 'MyBreaks' not found". My code is:

.e <- environment()
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks)), environment = .e) +
  geom_histogram(binwidth=0.1, color="steelblue")

I have done basic programming before but R's learning curve is real steep! Would appreciate if someone can help!

Thanks in advance!

Était-ce utile?

La solution

This is from Roland's comment here How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.).

ggplot(c, aes(x=b, fill=cut(..x.., breaks=get("MyBreaks", envir=.GlobalEnv)))) +
geom_histogram(binwidth=0.1, color="steelblue")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top