R中的日期无法使用GGPLOT2正确绘制

时间:2018-06-21 18:28:36

标签: r ggplot2

我是GGPLOT2的新手,但是有一个我不太了解的问题。我有使用GEOM_POINT和GEOM_LINE创建的绘图。一切看起来都很不错,除了日期没有按我期望的那样绘制。我有10个日期-4/6 / 2018、4 / 11 / 2018、4 / 20 / 2018、4 / 25 / 2018、5 / 11 / 2018、5 / 16 / 2018、5 / 25 / 2018、5 / 30 / 2018,6/8/2018 6/13/2018。即使我将ARRANGE与DPLYR结合使用,我的情节也会在2018年4月25日之后以4/6/2018返回这些结果。对新手有帮助吗?代码是:

library(ggplot2)
library(dplyr)
library(plotly)
library(sqldf)
library(tidyverse)
library(lubridate)
library(rio) #lets you use "import" for any file - without using extension name
options(scipen =999) #disable scientific notation
windowsFonts(adi=windowsFont("TT adineue PRO Black")) #define adineue PRO Black font to use later

#prepare data:

setwd("C:/Users/hayescod/Desktop/BuysToForecastTracking")
Buys_To_Forecast <- import("BuysToForecastTrack.csv")
Buys_To_Forecast[is.na(Buys_To_Forecast)] <- " " #replace all NA with blanks

colnames(Buys_To_Forecast) <- c("Date", "BusinessSegment", "Material", "StockNumber", "POCreatedBy", "PlantCode", "StockCategory", "Description", "Excess", "QuantityBought", "WareHouseSalesOrders", "GrandTotal", "Comments" )
Buys_To_Forecast$PlantCode <-factor(Buys_To_Forecast$PlantCode) #update PlantCode to factor
Buys_To_Forecast$QuantityBought <- as.numeric(Buys_To_Forecast$QuantityBought)
Buys_To_Forecast$Date <- as.Date(Buys_To_Forecast$Date, format = %m%d%Y)


#use DPLYR to filter data: 

btf <- Buys_To_Forecast %>%
  group_by(Date, Comments) %>%
  summarize(QuantityBought = sum(QuantityBought)) %>%
  arrange(Date) %>%
  ungroup()

#use ggplot:

btfnew <- ggplot(data=btf, aes(x=Date, y=QuantityBought, group=1, color=Comments)) + #note to use group when COMBINING geom_point and geom_line
  geom_point(size=8) + 
  geom_line(size=3) +
  facet_grid(Comments~.,scales="free_y")+ #make the Y axis "free"
  xlab("Date") + 
  ylab("Quantity") +
  ggtitle("Buys To Forecast Trend")+
  theme_dark() +
  theme(plot.title = element_text(hjust = 0.5, size=30,color="Black",family="adi"), 
        axis.title.x = element_text(color="DarkGray", size = 24,family="adi"), 
        axis.title.y = element_text(color="DarkGray", size = 24,family="adi"),
        axis.text.x = element_text(size=15),
        axis.text.y = element_text(size=15),
        legend.title = element_text(size=24, family="adi"),
        legend.text = element_text(size=12),
        strip.text = element_text(size=15))

#display the plot in ggplot and add limits to the axis: 

btfnew + 
  expand_limits(y = 0) #way to force set axis' to 0 - in this case the Y axis to be uniform across facets

1 个答案:

答案 0 :(得分:0)

您应该包括一个可重现的示例,以便我们可以准确了解您的数据正在发生什么。但是问题可能出在解析上。

您可以尝试使用mdy()包中的lubridate函数来解析日期变量。

希望它会有所帮助:)