ggplot:离散x轴的线图 [英] ggplot: line plot for discrete x-axis

查看:115
本文介绍了ggplot:离散x轴的线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表,但经过多次尝试后仍无法绘制数据,因此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") 

解决方案

可重现的示例:

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

将年份指定为有序因子将确保x轴的排序正确,而不考虑水平出现的顺序(而在绘图美学中仅使用"factor(year)"可能会导致问题). /p>

I have the following table but after many tries have been unable to plot the data so that the x-axis tick marks line up with the year. I have found solutions to boxplots, but not for geom_line()

How can I make discrete labels for year?

the following solutions did not work

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

解决方案

Reproducible example:

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

Specifying the year as an ordered factor will ensure that the x axis is ordered appropriately, regardless of the order in which the levels appear (whereas just using "factor(year)" in the plotting aesthetic could lead to issues).

这篇关于ggplot:离散x轴的线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆