简体   繁体   English

更改 ggplot 中 x 轴标签的顺序

[英]Changing order of x-axis labels in ggplot

I have dates as 'Dec-17','Jan-18','Feb-18','Mar-18','Apr-18','May-18','Jun-18','Jul-18','Aug-18' When I plot I need to preserve this in x axis.我的日期为'Dec-17','Jan-18','Feb-18','Mar-18','Apr-18','May-18','Jun-18','Jul-18','Aug-18'当我绘图时,我需要将其保留在 x 轴上。 But x axis is getting reordered.但是 x 轴正在重新排序。 I tried factors method, then also I get the same :我尝试了因素方法,然后我也得到了相同的结果:

> data_$Dates
[1] Apr-18 Aug-18 Dec-17 Feb-18 Jan-18 Jul-18 Jun-18 Mar-18 May-18
9 Levels: Apr-18 Aug-18 Dec-17 Feb-18 Jan-18 Jul-18 Jun-18 ... May-18

But, I need to follow the same formatting starting from Dec-17 and not Apr-18 My code :但是,我需要从Dec-17而不是Apr-18 Dec-17开始遵循相同的格式我的代码:

data_$Dates <- factor(data_$Dates, levels = data_$Dates[order(data_$`Expected`)])
data_$Dates
ggplot(data=data_, aes(x=Dates, y=`Expected`, group=1)) +
  geom_line()+
  geom_point()

You're reordering alphabetically.您正在按字母顺序重新排序。 You'll probably want to either convert your data to a data type that is interpreted as such (as suggested by @Wimpel in his/her comment).您可能希望将数据转换为这样解释的数据类型(如@Wimpel 在他/她的评论中所建议的那样)。 Alternatively, as you only have 9 unique values, you may want to reorder manually:或者,由于您只有 9 个唯一值,您可能需要手动重新排序:

date_$Dates <- factor(date_$Dates, levels = c("Dec-17", "Jan-18", "Feb-18"))

(which you'll have to expand to include the six months I have omitted). (您必须扩展以包括我省略的六个月)。

Let's generate some sample data first:让我们先生成一些示例数据:

set.seed(123)
data_ <- data.frame(Expected = sample(1:10, 9), Dates = c('Dec-17','Jan-18',
    'Feb-18','Mar-18', 'Apr-18', 'May-18','Jun-18', 'Jul-18', 'Aug-18'),
    stringsAsFactors = FALSE)

As @Wimpel told, the most natural way is to transform your data-column into a Data-type column.正如@Wimpel 所说,最自然的方法是将数据列转换为数据类型列。 Here you may find a comprehensive discussion on possible ways for that.在这里,您可以找到有关可能的方法的全面讨论。 One of the most convenient solutions is using of the lubridate package:最方便的解决方案之一是使用 lubridate 包:

library(lubridate)
data_$Dates_data <-  as.Date(parse_date_time(data_$Dates, "m-y"))

Now you have a date-formatted column to be used as x-data, and you may adjust the format of x labels according to your preferences (again, as @Wimpel suggested):现在您有一个日期格式的列用作 x 数据,您可以根据自己的喜好调整 x 标签的格式(同样,正如@Wimpel 建议的那样):

pl_1 <- ggplot(data = data_, aes(x = Dates_data, y = Expected, 
    group = 1)) +
  geom_line() +
  geom_point() +
  scale_x_date(date_labels = "%b-%y", date_breaks = "1 month")
plot(pl_1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM