獲取當(dāng)前時(shí)間
current_time <- Sys.time()
print(current_time)
使用 lubridate 包(如果未安裝請(qǐng)先安裝)
install.packages("lubridate")
創(chuàng)建一個(gè)簡(jiǎn)單的時(shí)鐘顯示,12點(diǎn)鐘在上
library(plotrix)
12點(diǎn)鐘在下方的基礎(chǔ)時(shí)鐘
plot_clock_12_bottom <- function() {
current <- Sys.time()
hours <- as.numeric(format(current, "%H"))
minutes <- as.numeric(format(current, "%M"))
seconds <- as.numeric(format(current, "%S"))
# 轉(zhuǎn)換為角度 - 12點(diǎn)鐘在下方(0度)
hour_angle <- (hours %% 12 + minutes/60) * 30 # 0度在12點(diǎn)鐘位置
minute_angle <- minutes * 6 # 0度在12點(diǎn)鐘位置
second_angle <- seconds * 6 # 0度在12點(diǎn)鐘位置
# 創(chuàng)建繪圖區(qū)域
plot(0, 0,
xlim = c(-1.2, 1.2),
ylim = c(-1.2, 1.2),
type = "n",
axes = FALSE,
xlab = "",
ylab = "",
asp = 1,
main = paste("時(shí)鐘 - 12點(diǎn)鐘在上\n", format(current, "%Y-%m-%d %H:%M:%S")))
# 繪制時(shí)鐘外圈
draw.circle(0, 0, 1, border = "black", lwd = 2)
# 繪制刻度 - 12點(diǎn)鐘在下
for(i in 0:11) {
# 從12點(diǎn)(下方)開(kāi)始,順時(shí)針計(jì)算角度
angle <- i * 30 * pi/180 # 0度在12點(diǎn)鐘位置
# 小時(shí)數(shù)字 - 12在下,3在左,6在上,9在右
hour_num <- ifelse(i == 0, 12, i)
# 計(jì)算數(shù)字位置
text_x <- 0.85 * sin(angle)
text_y <- 0.85 * cos(angle)
# 繪制小時(shí)數(shù)字
text(text_x, text_y, hour_num, cex = 1.2, font = 2)
# 繪制小時(shí)刻度線
inner_x <- 0.9 * sin(angle)
inner_y <- 0.9 * cos(angle)
outer_x <- 1.0 * sin(angle)
outer_y <- 1.0 * cos(angle)
segments(inner_x, inner_y, outer_x, outer_y, lwd = 2)
}
# 繪制時(shí)針
hour_x <- 0.5 * sin(hour_angle * pi/180)
hour_y <- 0.5 * cos(hour_angle * pi/180)
arrows(0, 0, hour_x, hour_y, lwd = 4, col = "blue", length = 0.1)
# 繪制分針
minute_x <- 0.8 * sin(minute_angle * pi/180)
minute_y <- 0.8 * cos(minute_angle * pi/180)
arrows(0, 0, minute_x, minute_y, lwd = 3, col = "green", length = 0.1)
# 繪制秒針
second_x <- 0.9 * sin(second_angle * pi/180)
second_y <- 0.9 * cos(second_angle * pi/180)
arrows(0, 0, second_x, second_y, lwd = 2, col = "red", length = 0.1)
# 添加中心點(diǎn)
points(0, 0, pch = 19, cex = 1.5, col = "black")
}
# 顯示時(shí)鐘
plot_clock_12_bottom()
# 方法1:for循環(huán),執(zhí)行60次,每次間隔1秒
for (i in 1:60) {
plot_clock_12_bottom() # 執(zhí)行命令p
Sys.sleep(1) # 等待1秒
}

image.png