2016-02-04 93 views
1

我有以下表格,但經過多次嘗試後,無法繪製數據,因此x軸刻度線與年份對齊。我已經找到解決方案,但不適用於geomline()ggplot geomline離散x軸標題

如何製作年份的離散標籤?

以下解決方案沒有工作

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

您是否打算2014年在標籤中列出兩次? – drhagen

+2

在'aes()'中使用'as.factor(year)''' – mtoto

+0

不,只是一次,那是一個錯誤 – iskandarblue

回答

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軸的排列順序適當,而不管層次出現的順序如何(而在繪圖美學中僅使用「因子(年份)」可能會導致問題)。