R 因子转换后的回归线丢失
在下面的图中,R 因子转换后的回归线丢失,r,ggplot2,R,Ggplot2,在下面的图中,时间位于x轴上,但不显示每年的记号: ggplot(mm, aes(x = time, y = value)) + geom_point(aes(color = variable)) + geom_line(stat = "smooth", method = "lm", alpha = 0.5) + facet_grid(variable ~ ., scales = "free_y") + theme(legend.position="non
时间
位于x轴上,但不显示每年的记号:
ggplot(mm, aes(x = time, y = value)) +
geom_point(aes(color = variable)) +
geom_line(stat = "smooth", method = "lm", alpha = 0.5) +
facet_grid(variable ~ ., scales = "free_y") +
theme(legend.position="none") +
coord_fixed(ratio = 10)
为了解决这个问题,我将时间
变量转换为一个因子,该因子起作用,但随后线性回归消失:
ggplot(mm, aes(x = factor(time), y = value)) +
geom_point(aes(color = variable)) +
geom_line(stat = "smooth", method = "lm", alpha = 0.5) +
facet_grid(variable ~ ., scales = "free_y") +
theme(legend.position = "none") +
coord_fixed(ratio = 10)
对于这一点,是否有一种解决方法,可以使用
geom\u line
?我认为scale\u x\u date
是您需要的
首先,一些可再现的数据:
df <-
data.frame(
y = 99:117
, x = seq(as.Date("1999-01-01")
, as.Date("2017-01-01")
, "year")
)
给予
或者,如果您的年份只是数字(而不是日期),您可以使用scale\u x\u continuous
获得类似效果:
df <-
data.frame(
y = 99:117
, x = 1999:2017
)
ggplot(df, aes(x = x, y = y) ) +
geom_smooth(method = "lm") +
geom_point() +
scale_x_continuous(breaks = pretty(df$x)
, minor_breaks = unique(df$x)) +
theme_gray()
df我认为scale\u x\u date
是您需要的
首先,一些可再现的数据:
df <-
data.frame(
y = 99:117
, x = seq(as.Date("1999-01-01")
, as.Date("2017-01-01")
, "year")
)
给予
或者,如果您的年份只是数字(而不是日期),您可以使用scale\u x\u continuous
获得类似效果:
df <-
data.frame(
y = 99:117
, x = 1999:2017
)
ggplot(df, aes(x = x, y = y) ) +
geom_smooth(method = "lm") +
geom_point() +
scale_x_continuous(breaks = pretty(df$x)
, minor_breaks = unique(df$x)) +
theme_gray()
df只需在scale_x_continuous
中设置断点。或者将x轴转换为posixct并格式化标签以仅显示年份只需在scale_x_continuous
中设置断点。或者将x轴转换为posixct并格式化标签以仅显示年份