我有一個按月列出的最大行程長度表,我試圖在 R
中繪制它,在嘗試繪制它時,X 軸沒有根據月份繪制,而是按字母順序繪制

我剛剛開始使用 R,我使用了我觀看的視頻之一中的以下代碼為我的表名進行了調整:
max_trips <- read.csv("max_and_min_trips.csv")
ggplot(data=max_trips)
geom_point(mapping = aes(x=month,y=max_trip_duration))
scale_x_month(month_labels = "%Y-%m")
uj5u.com熱心網友回復:
簡單的答案是“月”列的資料存盤為字串向量,而不是日期。在 R 中,這種資料型別稱為“字符”(或chr)。您可以通過鍵入 來確認這一點class(max_trips$month)。結果肯定"character"在您的控制臺中。scale_x_date因此,您的解決方案是 (1) 將資料型別轉換為日期和 (2) 使用和/或相關函式調整 x 軸上日期的格式。
我將使用一個簡單的示例資料集和繪圖來演示該程序。這是基本的資料框和繪圖。您會看到,如果這些mydf$dates值以“月/年”格式存盤為日期,則該圖再次“按字母順序”排列,而不是按預期排列。
library(lubridate)
mydf <- data.frame(
dates = c("1/21", "2/20", "12/21", "3/19", "10/19", "9/19"),
yvals = c(13, 31, 14, 10, 20, 18))
ggplot(mydf, aes(x = dates, y = yvals)) geom_point()

轉換為日期
要轉換為日期,您可以使用幾個不同的函式,但我發現這個lubridate包在這里特別有用。該as_date()函式將用于轉換;但是,我們不能直接申請as_date(),mydf$dates否則我們會在控制臺中收到以下錯誤:
> as_date(mydf$dates)
[1] NA NA NA NA NA NA
Warning message:
All formats failed to parse. No formats found.
由于您可以通過多種方式格式化與日期、日期時間等對應的資料,因此我們需要指定我們的資料為“月/年”格式。這里的另一個關鍵是資料設定為日期必須指定年、月和日。我們這里的資料只是指定了月份和年份,因此我們首先需要在轉換之前為每個日期添加一個隨機“日”。這是可行的:
mydf$dates <- as_date(
paste0("1/", mydf$dates), # need to add a "day" to correctly format for date
format = "%d/%m/%y" # nomenclature from strptime()
)
該paste0(...)函式用于"1/"在每個值之前添加mydf$dates,然后format =引數指定字符值應讀取為“日/月/年”。有關日期格式命名法的更多資訊,請參閱
如果標簽不是您想要的,您可以查看
在 OP 的情況下,我建議以下代碼應該可以作業:
library(lubridate)
max_trips <- read.csv("max_and_min_trips.csv")
max_trips$month <- as_date(
paste0("1/", max_trips$month),
format = "%d/%m/%y")
ggplot(data=max_trips)
geom_point(mapping = aes(x=month,y=max_trip_duration))
scale_x_date(breaks = "1 month", date_labels = "%Y-%m")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530259.html
標籤:rggplot2几何点
上一篇:跨時間繪制值為1的二進制變數
下一篇:每2秒一次,將物件移動到隨機坐標
