首页 文章

如何制作基本的ggplot2时间序列图

提问于
浏览
-2

我需要图表

sat -0.038685744            
sun -0.004397419            
mon -0.072163337            
tue 0.123328564         
wed 0.021875962         
thu 0.005030862         
fri 0.002869955

但是r-graph-gallery上的步骤令人困惑,所以有人可以通过一个简单的图表来帮我解决,该图表显示 ggplot2 中x轴上的星期几?

2 回答

  • 1

    以下是我将样本数据转换为数据帧的方法(尽管下次您真的应该使用 dput 来共享数据):

    df = read.table(text = "
                sat -0.038685744            
                sun -0.004397419            
                mon -0.072163337            
                tue 0.123328564         
                wed 0.021875962         
                thu 0.005030862         
                fri 0.002869955 ")
    colnames(df) = c("day", "thing")
    

    以下是我将数据框转换为条形图的方法:

    library(ggplot2)
    ggplot(df, aes(day, thing)) + geom_bar(stat = "identity")
    
  • 2

    下次以可重复的方式呈现数据,以便其他人不再重新键入它 .

    # your data 
    df <- tribble(
      ~week_day, ~value,
      "sat", -0.038685744,            
      "sun", -0.004397419,           
      "mon", -0.072163337,            
      "tue", 0.123328564,         
      "wed", 0.021875962,         
      "thu", 0.005030862,         
      "fri", 0.002869955 
    )
    df
    
    ordered <- c("sun", "mon", "tue", "wed", "thu", "fri", "sat")
    df$week_day <- factor(df$week_day, levels = ordered)
    
    ggplot(df, aes(x = week_day, y = value, group = 1)) +
      geom_point() +
      geom_line()
    

    [代码根据Gregor的建议调整]

相关问题