0

Why is the geom_smooth line not showing up in the plot generated by the following code?

test <- function() {
  require(ggplot2)
  # browser()
  set.seed(1);

  df <- data.frame(matrix(NA_real_, nrow = 50, ncol = 2))
  colnames(df) <- c("xdata", "ydata")

  df$xdata = as.numeric(sample(1:100, size = nrow(df), replace = FALSE))
  df$ydata = as.numeric(sample(1:3, size = nrow(df), prob=c(.60, .25, .15), replace = TRUE))

  plot1 <- ggplot(df, aes(x = reorder(xdata,-ydata), y = ydata)) + 
    geom_point(color="black") + 
    geom_smooth(method = "loess") + 
    theme(legend.position = "none", axis.text.x = element_blank(), axis.ticks.x = element_blank() )
  plot1
}
test()

My x and y data is definitely numeric, as advised in this question: geom_smooth in ggplot2 not working/showing up

Plot:

enter image description here

2
  • What happens when you remove the call to reorder? Commented Dec 8, 2018 at 2:17
  • @jdobres - the curve comes back! But I do need the reorder for my actual code (this is just an example). What would you suggest? Commented Dec 8, 2018 at 2:19

1 Answer 1

4

The xdata and ydata may be numeric, but the geom_smooth doesn't seem to be recognising your reorder function output as such. If you wrap as.numeric around the reorder part, the line comes back:

ggplot(df, aes(x = as.numeric(reorder(xdata,-ydata)), y = ydata)) + 
  geom_point(color="black") + 
  geom_smooth(method = "loess") + 
  theme(legend.position = "none", axis.text.x = element_blank(), 
        axis.ticks.x = element_blank())

reorder wrapped in as numeric

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.