我有以下資料:
structure(list(Month = structure(c(17744, 17775, 17805, 17836,
17866, 17897, 17928, 17956, 17987, 18017, 18048, 18078, 18109,
18140, 18170, 18201, 18231, 18262, 18293, 18322, 18353, 18383
), class = "Date"), Return = c(0.1, 0.4, 0.5, 0.2, -0.5, 0.2,
4, 0.3, 0.1, 0.4, 0.5, 0.2, -0.5, 0.2, 4, 0.3, 0.4, -0.5, 0.2,
0.3, 0.4, -0.5), Rating = c("1", "1", "NA", "5", "3", "NA", "3",
"4", "4", "NA", "5", "5", "NA", "1", "1", "1", "1", "1", "2",
"2", "2", "2")), row.names = c(NA, -22L), class = "data.frame")
我想用 x 軸上的“月”和 y 軸上的“回傳”來繪制資料。首先,我對我的資料進行了一些調整:
library(data.table)
library(magrittr)
library(ggplot2)
library(zoo)
Data <- Data %>%
mutate(Rating = fifelse(is.na(Rating),"NA",as.character(Rating)))
Data$Month <- as.Date(as.yearmon(Data$Month, format="%Y-%m") )
然后我使用以下代碼:
ggplot(Data, aes(x=`Month`, y=`Return`, group=`Rating`, fill=`Rating`, color=`Rating`))
geom_line(size=1)
scale_color_brewer(palette="Paired")
scale_x_date(date_breaks ="6 months", date_labels = "%Y-%m")
然后我在 y 軸和圖表的線條之間有一些空間。然后我運行以下代碼來消除空間(包括 expand=c(0,0)):
ggplot(Data, aes(x=`Month`, y=`Return`, group=`Rating`, fill=`Rating`, color=`Rating`))
geom_line(size=1)
scale_color_brewer(palette="Paired")
scale_x_date(date_breaks ="6 months", date_labels = "%Y-%m", expand=c(0,0))
但是,當我 expand=c(0,0)在 x 軸上添加時,顯示的第一個日期也會發生變化,并且非常靠近我不喜歡的 y 軸。現在 2018-08 是 x 軸上的第一個月。但是,在我更喜歡 2018-12 之前。我該如何更改它,以便我再次將 2018-12 年作為 x 軸上被標記的第一個月。
uj5u.com熱心網友回復:
正如我在評論中提到的,如果您想要特定的休息時間,那么恕我直言,您最好使用breaks引數明確設定休息時間。
此外,請注意您已使用as.Date. 從您在評論中提到的錯誤訊息中,我猜您已經錯過了:
library(ggplot2)
ggplot(Data, aes(x = `Month`, y = `Return`, group = `Rating`, fill = `Rating`, color = `Rating`))
geom_line(size = 1)
scale_color_brewer(palette = "Paired")
scale_x_date(breaks = seq.Date(as.Date("2018-12-01"), as.Date("2020-12-01"), by = "6 months"),
date_labels = "%Y-%m", expand = c(0.005, 0))

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/466733.html
上一篇:基于具有相同變數的兩組創建圖
