如何在 ggplot2 中重新排序数字 x 轴?

How to reorder a numeric x-axis in ggplot2?

第一次发帖,如有错误请多多包涵

我试图绘制从 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 = 7) 开始 x 轴。如果我将 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() 的 'white' 部分实际上从 7 月开始,这就是为什么我希望我的 x 轴从这里开始。

如有任何帮助,我们将不胜感激!

干杯,

我添加了一个 xlim(7,12) 并将 scale_fill_gradient 中的 de midpoint 参数更改为 9.5

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 = 9.5)+
  theme(legend.position = "none")+
  xlim(7,12)+
  geom_tile(data = tile.df, aes(y = y, fill = x), height = 0.5)

您可以按数字重新排列您的月份,然后以正确的顺序添加标签:

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)

(绘制同一张图)

reprex package (v2.0.1)

创建于 2022-05-12