【问题标题】:R data not being plotted correctlyR数据未正确绘制
【发布时间】:2020-08-31 21:18:01
【问题描述】:

我真的在用 ggplot 和 dplyr 处理 R 中的情节。

我有一个带有列的数据框:

Customer.Name, Customer.Code, Product, Date, Platform, Input.Records, Output.Records

我使用 dplyr 进行了分组,按日期对输入记录进行分组。

df$Date <- as.Date(df$Date, format = "%Y-%m-%d")
dateGrouping <- df%>% group_by(`Date`) %>% summarise(`Input.Records` = sum(`Input.Records`))

然后我尝试绘制它。

myPlot <- ggplot(data=dateGrouping, aes(x=factor(Date), y=`Input.Records`, group=1)) +
  geom_line() + ylim(0, 85000000)
myPlot

但是输出看起来不对,看起来像条形图,线之间没有连接

所以我把geom_line() 换成了geom_path()

而且这看起来肯定是错误的......为什么路径来回走动?应该是从左到右的直线轨迹吧?

这是复制示例的代码。仅包含分组帧的代码,因为完整文件太大且包含机密数据。

   library(ggplot2) 
   library(dplyr) 
   df <- data.frame("Date" = c( "2020-08-10", "2020-08-11", "2020-08-12", "2020-08-13", "2020-08-14", "2020-08-15", "2020-08-16", "2020-08-17", "2020-08-18",
 "2020-08-19", "2020-08-20", "2020-08-21", "2020-08-22", "2020-08-23", "2020-08-24"),
 "Input.Records" = c(19501675,19298520,75546425,90104271,34139598,35384083,11849216,21996019,241643844,55643434,20733736,46198249,9815057,78211864,103263783))
    
    myPlot <- ggplot(data=df, aes(x=factor(Date), y=`Input.Records`, group=1)) +
      geom_path() + ylim(0, 85000000)
    myPlot

【问题讨论】:

    标签: r dataframe ggplot2 plot dplyr


    【解决方案1】:

    我认为这就是您要寻找的。我对你的代码做了一些小改动:

    library(ggplot2)
    #Plot
    ggplot(data=df, aes(x=Date, y=Input.Records, group=1)) +
      geom_line()
    

    输出:

    让我知道这是否适合你。

    【讨论】:

    • 这确实是我想要的输出,但是你做了什么改变?除去 factor() 和反引号后,代码看起来完全相同。
    • @Elmambo2194 只需删除您在 y 轴上设置的限制并尝试绘图,我相信这应该可以缓解问题!如您所见,这条线创建得很完美!
    • 谢谢,它确实有效。如果我使用限制,我会收到消息Warning message: Removed 1 row(s) containing missing values (geom_path).。有什么理由吗?另外,如果我需要另一个问题也没关系,但是有没有办法让 Y 标签显示为 80,000,000 之类的数字而不是科学记数法?
    • @Elmambo2194 当您看到行被删除是因为限制。一行必须超出限制,然后被删除。对于您所说的,您可以在您的geom_line() 之后添加scale_y_continuous(labels = scales::comma),所以它应该是geom_line()+scale_y_continuous(labels = scales::comma),也感谢您!
    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 2021-12-04
    • 2013-02-25
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多