为什么以下代码生成的绘图中没有显示geom_smooth线?
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()
我的x和y数据绝对是数字的,如以下问题所述:geom_smooth in ggplot2 not working/showing up
图:
答案 0 :(得分:2)
xdata
和ydata
可能是数字,但是geom_smooth
似乎并不能识别您的reorder
函数输出。如果将as.numeric
包装在重排零件周围,则该行会返回:
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())