ggplot2:使用自定义月标签覆盖scale_x_datetime

时间:2017-06-24 03:25:01

标签: r ggplot2

以下是我的一些数据:

df <- structure(list(farm = c("F1", "F1", 
"F1", "F1"), index = structure(c(1L, 
1L, 4L, 4L), .Label = c("HT", "Mid-T", "Outside Mid-T", "Outside South"
), class = "factor"), sensorheight = c(1L, 1L, 1L, 1L), yrmonth = structure(c(1491004800, 
1496275200, 1491004800, 1496275200), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), monthindex = structure(c(2L, 2L, 2L, 2L), .Label = c("Spring", 
"Winter"), class = "factor"), N = c(2, 2, 1, 1), TempC = c(2.06446759259259, 
6.68402777777778, 1.32268518518518, 5.63194444444445), sd = c(1.17081824208967, 
0.034373246307681, NA, NA), se = c(0.827893518518518, 0.0243055555555567, 
NA, NA), ci = c(10.5193845460483, 0.308831365115372, NA, NA)), .Names = c("farm", 
"index", "sensorheight", "yrmonth", "monthindex", "N", "TempC", 
"sd", "se", "ci"), row.names = c(7L, 9L, 20L, 22L), class = "data.frame")

我想在x轴上用自定义月份标签绘制图形:

labels <- c('March*', 'April', 'May*', 'June', 'July')

当我添加标签时,它不会按正确的顺序放置标签:

ggplot(df, aes(x=yrmonth,y=TempC)) +    
   geom_line(size=.4) +    
   geom_point(size=1.5) +      
   scale_x_datetime(name = " ", date_breaks = "1 month", date_labels = labels) +   
   scale_y_continuous(name = "Monthly Average Maximum Temperature at 1 m (°C)")

1 个答案:

答案 0 :(得分:2)

您可以通过因子级别定义订单

labels <- c("March*", "April", "May*", "June", "July")
labels <- factor(labels,levels=labels)