我有 CSV 資料,其中有兩列,我需要將時間繪制為 x 軸并計為 y 軸。資料中的時間范圍為 2008 年 9 月至 2021 年 12 月。資料點為每月。
這是我的 csv 格式
我想在 x 軸上放置 5 個特定時間點,如下所示:

這是我嘗試過的:
library(ggplot2)
theme_set(
theme_bw(),
theme(legend.position = "top")
)
result <- read.csv("Downloads/Questions Trend - Questions Trend.csv")
p <- ggplot(result, aes(result$Time_Formatted, result$VCS_Feature_History_Sanitize_Trnd))
geom_point(size = 0.1) xlab("Month") ylab("Temporal Trend")
p geom_smooth(method = "loess", color = "red")
我在下面嘗試過,可以洗掉一些點,但仍然無法自定義特定點。
library(ggplot2)
library(scales)
theme_set(
theme_bw(),
theme(legend.position = "top")
)
result <- read.csv("Downloads/Questions Trend - Questions Trend.csv")
result$Time_Formatted <- as.Date(result$Time_Formatted)
p <- ggplot(result, aes(result$Time_Formatted, result$VCS_Feature_History_Sanitize_Trnd))
geom_point(size = 0.1) xlab("Month") ylab("Temporal Trend")
scale_x_date(date_breaks = "years" , date_labels = "%b-%y")
p geom_smooth(method = "loess", color = "red")

如何在 x 軸上給出特定點?
uj5u.com熱心網友回復:
你應該使用包的scale_x_date()功能ggplot2。
例如,當我需要繪制時間資料時,我總是在作業中使用以下代碼:
ggplot2::scale_x_date(name = " ",
breaks = function(date) seq.Date(from = lubridate::ymd("2020-01-01") 1,
to = lubridate::today(),
by = "1 month"),
limits = c(lubridate::ymd("2020-07-13"),
lubridate::today()),
expand = c(0,0),
labels = scales::date_format("%b %Y"))
使用breaks,您可以選擇僅顯示每個月的第一個日期。
有了labels和包中的功能date_format(),scales你可以選擇日期格式,基本上你可以做任何你想做的事情。在這里,我選擇用字母繪制月份,用數字繪制年份。
uj5u.com熱心網友回復:
這里的大多數問題都與讀取日期資料有關,以便正確識別格式 - 這可以通過明確指定來完成:
result <- read.csv("Test.csv")
result$Time_Formatted <- as.Date(result$Time_Formatted, "%m/%d/%y")
然后,它只是制作一個向量來指示您想要中斷的位置并在scale_x_datewith 中指定它的情況:
date_breaks <- as.Date(c("1/7/10", "1/12/12", "1/1/14", "1/2/15", "1/3/16"), "%d/%m/%y")
p <- ggplot(result, aes(Time_Formatted, VCS_Feature_History_Sanitize_Trnd))
geom_point(size = 0.1) xlab("Month") ylab("Temporal Trend")
scale_x_date(breaks=date_breaks , date_labels = "%b-%y")
p geom_smooth(method = "loess", color = "red")
請注意,我已經洗掉了函式中對“結果”的顯式參考,aes()因為這是不必要的,并且根據它創建的警告而被貶低。最終結果是:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440275.html
