首页 文章

ggplot:离散x轴的线图

提问于
浏览
1

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

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

以下解决方案无效

g + scale_x_discrete(limits=c("2013","2014","2015"))
g + scale_x_discrete(labels=c("2013","2014","2015"))
distance_of_moves
  distance moved year
1       2.914961 2013
2       2.437516 2014
3       2.542500 2015
ggplot(data = distance_of_moves, aes(x = year, y = `distance moved`, group = 1)) +
 geom_line(color = "red", linetype = "dashed", size = 1.5) +
 geom_point(color = "red", size = 4, shape = 21, fill = "white") + 
 ylab("Average distance of movement") + 
 xlab("year")

enter image description here

1 回答

  • 0

    可重复的例子:

    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()
    

    enter image description here

    将年份指定为有序因子将确保x轴被适当地排序,而不管水平出现的顺序(而在绘图美学中仅使用“因子(年)”可能导致问题) .

相关问题