scale_x_discrete&消失的标签

时间:2018-03-20 01:28:32

标签: r ggplot2

我有以下代码

times=c(0:23)
               ggplot(TravelTimes, aes(x=Times))+labs(y="# Flights",x = "Times") + 
        scale_x_discrete( name ="hour",breaks=c(0:23),limits=times)+ ###lastchange
        geom_point(aes(y = TravelTimes[[2]], colour = "Arrivals",group=1))+
        geom_point(aes(y = TravelTimes[[3]], colour = "Departures",group=1))+
        geom_line(aes(y = TravelTimes[[2]], colour = "Arrivals",group=1))+
        geom_line(aes(y = TravelTimes[[3]], colour = "Departures",group=1))+
        theme(axis.text.x=element_text(angle = 90, hjust = 0))+ 
        scale_color_manual("legend", values = c("Departures" = colors[1], "Arrivals" = colors[2]))

TravelTimes如下所示

   Times Arrivals Departures

1      0        0         88

2      1        0         25
3      2        0          4
4      3        0          2
5      4        0         43
6      5        0        487
7      6        0        915
8      7        0       1829
9      8        0       1617
10     9        0       1547
11    10        0       1498
12    11        0       1007
13    12        0       2001
14    13        0       1548
15    14        0       1156
16    15        0       1513
17    16        0       1157
18    17        0       1624
19    18        0       1280
20    19        0       1674
21    20        0       1640
22    21        0       1521
23    22        0        532
24    23        0        254

它工作得非常好并产生以下图表
      click for correct graph

然而,当我尝试改变"时代"我遇到标签消失的问题

      times=c("12AM","1AM","2AM","3AM","4AM","5AM","6AM","7AM","8AM","9AM","10AM","11AM","12PM","1PM","2PM","3PM","4PM","5PM","6PM","7PM","8PM","9PM","10PM","11PM")

click for incorrect graph

1 个答案:

答案 0 :(得分:0)

您可以相应地修改TravelTimes

TravelTimes$Times <- factor(times, levels = times)

其中levels的使用以所需方式订购小时。然后

ggplot(TravelTimes, aes(x = Times)) + labs(y = "# Flights") + 
  scale_x_discrete(name = "hour") +
  ...

似乎可以提供所需的输出。