如何在数据框中更改月份数​​?

时间:2017-10-11 02:14:52

标签: r dataframe ggplot2

我有一个像下面这样的csv文件。

year=c("2015","2016","2017")
month=c("1","2","3","4","5","6","7","8","9","10","11","12")
freq=c("10","12","16","12","21","16","23","22","20","19","21","15")
df=data.frame(year, month, freq)

ggplot(df, aes(x=month, y=freq, fill=year))+geom_bar(stat="identity)

axis.x显示1,10,11,12,2,3,4,5,6,7,8,9

我想要1,2,3,4,5,6,7,8,9,10,11,12

我该怎么办?

2 个答案:

答案 0 :(得分:0)

使用因素。在绘图之前尝试这个:

df$month <- factor(month, levels = 1:12)

如果必须,您可以手动设置级别,以便ggplot2遵循您选择的顺序。

答案 1 :(得分:0)

正如@alistaire所说,最好只从数字值开始,month以及所有其他变量:

month <- 1:12

然后要在x轴上获得正确的标签,请将其添加到ggplot的末尾:

+ scale_x_continuous(breaks = 1:12)