我正在 R 中創建一個圖表,顯示每月的乘車總數。其實,開始的月份是2020年4月,結束的月份是2021年3月。這樣的安排,對于別人的分析和解釋,有著重要的意義。但是,由于 R 自動從 1 => 12 排序,所以我想問一下是否有另一種方法可以重新排列它?
library(ggplot2);library(dplyr)
Bike %>%
group_by(member_casual, Date_month) %>%
summarise(.groups = 'drop',
average_duration = mean(Time_duration)) %>%
arrange(member_casual, Date_month) %>%
mutate(Average_Time = hms(average_duration)) %>%
ggplot(aes(
x = Date_month,
y = Average_Time,
group = member_casual,
colour = member_casual
))
geom_line() geom_point(size = 3)
scale_colour_manual(name = "Membership Type",
values = c(casual = '#ff9900', member = '#0099cc'))
labs(
title = "Average Ride Duration By Month",
x = "Month",
y = "Average Time",
subtitle = "April 2020 to March 2021"
)

uj5u.com熱心網友回復:
正如@rawr 提到的,您可以使用factor設定沿 x 軸的順序。
library(tidyverse)
data %>%
ggplot(aes(
x = factor(month, levels = c(4:12, 1:3)),
y = value,
group = group
))
geom_line()
geom_point(size = 3)
scale_colour_manual(name = "Membership Type",
values = c(casual = '#ff9900', member = '#0099cc'))
labs(
title = "Average Ride Duration By Month",
x = "Month",
y = "Average Time",
subtitle = "April 2020 to March 2021"
)
輸出

資料
data <- structure(
list(
group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
month = 1:12,
value = c(
22.1462195669301,
34.7227226593532,
11.3724566600285,
37.9181093303487,
11.8698693322949,
17.4393743579276,
21.4907402452081,
17.6362748816609,
29.6476712427102,
36.9375107018277,
25.3655201010406,
20.449273835402
)
),
class = "data.frame",
row.names = c(NA, -12L)
)
uj5u.com熱心網友回復:
如果您也有年份,則可以使用該包lubridate創建日期并沿 x 軸繪制該日期。那么順序應該是固定的,我認為名字看起來也更好。
以 Andrew 的例子為基礎,我們可以做這樣的事情:
library(dplyr)
library(ggplot2)
data %>%
mutate(date = lubridate::make_date(year = year, month = month)) %>%
ggplot(aes(
x = date,
y = value,
group = group
))
geom_line()
geom_point(size = 3)
scale_colour_manual(name = "Membership Type",
values = c(casual = '#ff9900', member = '#0099cc'))
labs(
title = "Average Ride Duration By Month",
x = "Date",
y = "Average Time",
subtitle = "April 2020 to March 2021"
)
輸出:

資料:
data <- structure(
list(
group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
month = 1:12,
year = c(rep(2021, 3), rep(2020, 9)),
value = c(
22.1462195669301,
34.7227226593532,
11.3724566600285,
37.9181093303487,
11.8698693322949,
17.4393743579276,
21.4907402452081,
17.6362748816609,
29.6476712427102,
36.9375107018277,
25.3655201010406,
20.449273835402
)
),
class = "data.frame",
row.names = c(NA, -12L)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/387225.html
上一篇:如何防止ggplot2(GADM)繪制所選州以外的地區
下一篇:如何向堆積條形圖添加標簽
