R语言 ggplot2:使用自定义月份标签覆盖scale_x_datetime

oyjwcjzk  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(162)

以下是我的一些数据:

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

pexxcrt21#

您可以通过因子水平定义订单

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

yhxst69z2#

date_labels = labels更改为POSIXlt;例如,要显示月和年,请使用scale_x_datetime(name = " ", date_breaks = "1 month", date_labels = "%b %Y")
此代码是在this link的教程中修改的

相关问题