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

r829
  • 161
  • 1
  • 10

1 Answers1

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

massisenergy
  • 1,764
  • 3
  • 14
  • 25
Andy Baxter
  • 5,833
  • 1
  • 8
  • 22