第一次發帖,如有錯誤請見諒。
我正在嘗試從 7 月開始繪制一年中的一些月度值。. 以下是一些示例資料:
x <- seq(1, 12, 1)
set.seed(2022)
y <- rnorm(n = 12)
df <- data.frame("x" = x, "y" = y)
ggplot(data = df, aes(x = x, y = y))
geom_line()
在這種情況下,我想在 7 月開始 x 軸(x = 7)。如果我將 x 軸變數轉換為因子,這很容易。但是,我需要將 x 軸保持為數字刻度,因為我正在嘗試使用 geom_tile 在背景中繪制一種標稱色標,如下所示:
tile.df <- data.frame(
"x" = seq(1, 12, by = 1/12), # Note how the color scale is much higher resolution than the data
"y" = -4
)
ggplot(data = df, aes(x = x, y = y))
theme_classic()
geom_line()
scale_x_continuous(breaks = seq(1, 12, 1))
scale_fill_gradient2(low = "black", mid = "gray", high = "white", midpoint = 6)
theme(legend.position = "none")
geom_tile(data = tile.df, aes(y = y, fill = x), height = 0.5)
在我的實際資料集中,geom_tile() 的“白色”部分實際上是在 7 月開始的,這就是為什么我希望我的 x 軸從這里開始。
對此的任何幫助將不勝感激!
干杯,
uj5u.com熱心網友回復:
您可以按數字重新排序月份,然后以正確的順序添加標簽:
library(ggplot2)
x <- seq(1, 12, 1)
set.seed(2022)
y <- rnorm(n = 12)
df <- data.frame("x" = x, "y" = y)
df$x <- 1 (df$x 5) %% 12
tile.df <- data.frame(
"x" = seq(1, 12, by = 1/12), # Note how the color scale is much higher resolution than the data
"y" = -4
)
ggplot(data = df, aes(x = x, y = y))
theme_classic()
geom_line()
scale_x_continuous(breaks = seq(1, 12, 1), labels = c(month.abb[7:12], month.abb[1:6]))
scale_fill_gradient2(low = "black", mid = "gray", high = "white", midpoint = 6)
theme(legend.position = "none")
geom_tile(data = tile.df, aes(y = y, fill = x), height = 0.5)

這條線df$x <- 1 (df$x 5) %% 12在幕后重新排序您的月份,以便繪制 July = 1,然后軸的標簽以新順序顯示月份。
一種更直觀的方法可能是轉換為一個因子,按您想要的順序放置,然后在繪圖時轉換回整數(同時類似地添加正確排序的標簽:
reordered_months <- c(month.abb[7:12], month.abb[1:6])
df$month <- factor(month.abb[df$x], levels = reordered_months)
ggplot(data = df, aes(x = as.numeric(month), y = y))
theme_classic()
geom_line()
scale_x_continuous(breaks = seq(1, 12, 1), labels = reordered_months)
scale_fill_gradient2(low = "black", mid = "gray", high = "white", midpoint = 6)
theme(legend.position = "none")
geom_tile(data = tile.df, aes(y = y, x = x, fill = x), height = 0.5)
(繪制相同的圖表)
由
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474402.html
下一篇:如何在R中建立斜率圖?
