ggplot:离散x轴的线图

时间:2016-02-04 18:47:20

标签: r ggplot2

我有下表但经过多次尝试后无法绘制数据,因此x轴刻度标记与meteor reset对齐。我找到了箱图的解决方案,但不是year

如何制作年份的离散标签?

以下解决方案无效

geom_line()
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 :(得分:1)

可重复的例子:

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轴的排序正确,无论水平出现的顺序如何(而在绘图美学中仅使用“因子(年)”可能会导致问题)。 / p>