Almighty
Almighty

Reputation: 25

Getting "missing aesthetics error" while using ggplot2's geom_errorbar

my code looks like this

Q <-  c(1.624e-05, 1.583e-05, 1.540e-05, 1.512e-05, 1.487e-05, 1.420e-05, 1.334e-05, 1.270e-05, 1.239e-05, 1.180e-05, 1.081e-05, 9.720e-06,  8.880e-06, 7.770e-06, 6.740e-06, 5.790e-06, 4.430e-06, 3.410e-06)
diP <- c(4443.93, 4022.10, 3698.37, 3423.69, 3237.30, 2943.00, 2668.32, 2501.55, 2383.83, 2148.39, 1952.19, 1618.65, 1422.45, 1177.20, 1010.43, 814.23, 559.17,  343.35)
eQ <- c(1.6e-06, 1.6e-06, 1.6e-06, 1.5e-06, 1.5e-06, 1.4e-06, 1.3e-06, 1.3e-06, 1.2e-06, 1.2e-06, 1.1e-06, 1.0e-06, 9.0e-07, 8.0e-07, 7.0e-07, 6.0e-07, 5.0e-07, 4.0e-07)
ediP <- seq(10,10,length=18)

ggplot() + stat_smooth(aes(diP[10:18],Q[10:18]),method = "lm",col="red",se=F) + geom_point(aes(diP,Q)) +
geom_errorbar(aes(ymin=Q-eQ, ymax=Q+eQ), width=.1) +
xlab(expression(paste(Delta,"p (Pa)"))) + ylab(expression(paste("Q (",m^3,"/s)")))

When I run all, I get the following error:

Error: geom_errorbar requires the following missing aesthetics: x or y, xmin and xmax

Ty in advance!

Upvotes: 1

Views: 354

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226532

You could provide x=diP as the x variable, but I'm going to recommend two best practices for working with ggplot: (1) use the data argument explicitly (don't grab variables from the global workspace) (2) allow aesthetics to be inherited whenever it makes sense. This gets me to:

dd <- data.frame(Q, diP, eQ, ediP)

ggplot(dd, aes(x=diP, y=Q)) +
  stat_smooth(data=dd[10:18,],
              method = "lm",col="red",se=FALSE) +
  geom_point() +
  geom_errorbar(aes(ymin=Q-eQ, ymax=Q+eQ), width=.1) +
  xlab(expression(paste(Delta,"p (Pa)"))) +
  ylab(expression(paste("Q (",m^3,"/s)")))

by specifying data=dd and the mapping in the initial ggplot(), you are allowing these mappings to be inherited by subsequent geoms. I overrode the data argument in the stat_smooth to make sure only the appropriate subset of the data got used.

Upvotes: 1

Related Questions