ggplot:离散 x 轴的线图

isk*_*lue 7 r ggplot2

我有下表,但经过多次尝试无法绘制数据,以便 x 轴刻度线与year. 我找到了箱线图的解决方案,但不适用于geom_line()

我怎样才能制作一年的离散标签?

以下解决方案不起作用

g + scale_x_discrete(limits=c("2013","2014","2015"))
g + scale_x_discrete(labels=c("2013","2014","2015"))
Run Code Online (Sandbox Code Playgroud)
distance_of_moves
  距离移动年
1 2.914961 2013
2 2.437516 2014
3 2.542500 2015

ggplot(data = distance_of_moves, aes(x = year, y = `distancemoved`, group = 1)) +
 geom_line(color = "red", linetype = "dashed", size = 1.5) +
 geom_point(color = "red", size = 4, shape = 21, fill = "white") + 
 ylab("平均移动距离") + 
 xlab("年") 

在此处输入图片说明

Eri*_*ric 10

可重现的例子:

data <- data.frame(dist=c(2.914, 2.437, 2.542), year=c(2013, 2014, 2015))
# this ensures that stuff will be ordered appropriately
data$year <- ordered(data$year, levels=c(2013, 2014, 2015))
ggplot(data, aes(x=factor(year), y=dist, group=1)) +
  geom_line() +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

将年份指定为有序因子将确保 x 轴正确排序,而不管级别出现的顺序如何(而在绘图美学中仅使用“因子(年份)”可能会导致问题)。

  • 你需要 ggplot2 中线条的群体美感;按照 ggplot2 的编写方式,您选择的特定几何图形将应用于相关分类变量的所有组合(即,在本例中为 x 轴的因子)。这不适用于线,因为它会导致每个点 1 条线(这不是一个东西)。因此,指定 group=1 告诉 ggplot 每个点都将与单线分组连接。 (3认同)
  • “group=1”有什么作用?顺便说一句,这个论坛上一定时间后应该有一些自动接受答案的功能。 (2认同)