如何在GGPLOT2中重新排序数字X轴?
第一次发布,所以请原谅我犯的任何错误。
我试图在一年的时间内(从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轴从这里开始。
在此方面的任何帮助将不胜感激!
干杯,
First time posting, so please forgive any errors I make.
I'm attempting to plot some monthly values over the course of a year, starting in July. . Here is some sample data:
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()
In this case, I would like to start the x-axis in July (x = 7). This is easy enough if I convert my x-axis variables to a factor. But, I need to keep the x-axis as a numeric scale because I'm attempting to use geom_tile to plot a sort of nominal color scale in the background, like so:
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)
In my actual dataset, the 'white' portion of the geom_tile() actually starts in July, which is why I'd like my x-axis to start here.
Any help in this would be greatly appreciated!
Cheers,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以按数值重新排序几个月,然后按正确的顺序添加标签:
行
df $ x&lt; -1 +(df $ x+5)%% 12
在幕后重新排序您的月份,以便绘制7月= 1,然后按新订单显示轴的标签。一种更直观的方法可能是将要素转换为您想要的顺序,然后在绘制绘制时转换回整数(同时添加正确订购的标签:(
绘制同一图)
在2022-05创建-12由 reprex package (v2.0.1)
You could reorder your months numerically then add labels in the correct order:
The line
df$x <- 1 +(df$x+5) %% 12
is behind the scenes reordering your months so that July = 1 to be plotted, then the labels of the axis show months in the new order.A more intuitive way may be to convert to a factor, put in the order you want, then convert back to an integer when plotting (whilst similarly adding the correctly ordered labels:
(plots the same graph)
Created on 2022-05-12 by the reprex package (v2.0.1)
我添加了一个xlim(7,12),并将scale_fill_gradient中的de midpoint参数更改为9.5
I added a xlim(7,12) and changed de midpoint argument in scale_fill_gradient to 9.5