我制作了这两个非常基本的数据框:
CollaroyPrices<-data.frame(years=c("Jan-2023", "Feb-2023", "Mar-2023", "Apr-2023", "May-2023", "Jun-2023", "Jul-2023",
"Aug-2023", "Sep-2023", "Oct-2023", "Nov-2023", "Dec-2023"),
medianprice=c(2700000, 2740000, 2920000, 2990000, 3100000, 3210000, 3220000, 3180000, 3200000, 3200000, 3130000, 3120000))
NSWPrices<-data.frame(years=c("Jan-2023", "Feb-2023", "Mar-2023", "Apr-2023", "May-2023", "Jun-2023", "Jul-2023",
"Aug-2023", "Sep-2023", "Oct-2023", "Nov-2023", "Dec-2023"),
medianprice=c(949000, 955000, 958000, 969000, 980000, 993000, 1000000, 1000100, 1000200, 1000200, 1000300, 1000300))
当我运行它们时,数据帧保持正确的顺序(例如,从一月运行到十二月):
> CollaroyPrices
years medianprice
1 Jan 2023 2700000
2 Feb 2023 2740000
3 Mar 2023 2920000
4 Apr 2023 2990000
5 May 2023 3100000
6 Jun 2023 3210000
7 Jul 2023 3220000
8 Aug 2023 3180000
9 Sep 2023 3200000
10 Oct 2023 3200000
11 Nov 2023 3130000
12 Dec 2023 3120000
但是,当我使用 ggplot2 制作基本折线图时,它会扰乱 x 轴:
ggplot()+
geom_line(data=CollaroyPrices, aes(x=years, y=medianprice, color="CollaroyPrices", group=1), size=1) +
geom_line(data=NSWPrices, aes(x=years, y=medianprice, color="NSWPrices", group=1), size=1)
有人可以帮助让 R 保留我输入的顺序吗?
你好,我明白了,
图书馆(forcats)
然后将 fct_inorder 添加到我的 ggplot 中以保持我插入因子变量的顺序:
ggplot()+ geom_line(data=CollaroyPrices, aes(x=fct_inorder(年), y=medianprice, color=“CollaroyPrices”, group=1), size=1) + geom_line(数据=NSWPrices,aes(x=fct_inorder(年),y=中位数价格,颜色=“NSWPrices”,组=1),大小=1)