【问题标题】:R: ggplot display all dates on x axisR:ggplot 在 x 轴上显示所有日期
【发布时间】:2017-06-10 20:59:00
【问题描述】:

我有以下数据集

structure(list(Date = structure(c(16636, 16667, 16698, 16728, 
16759, 16789, 16820, 16851, 16880, 16911, 16636, 16667, 16698, 
16728, 16759, 16789, 16820, 16851, 16880, 16911, 16636, 16667, 
16698, 16728, 16759, 16789, 16820, 16851, 16880, 16911, 16636, 
16667, 16698, 16728, 16759, 16789, 16820, 16851, 16880, 16911, 
16636, 16667, 16698, 16728, 16759, 16789, 16820, 16851, 16880, 
16911), class = "Date"), Wheel = structure(c(5L, 5L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 
12L, 12L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 11L, 11L, 11L, 
11L, 11L, 11L, 11L, 11L, 11L, 11L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L, 6L, 6L), .Label = c("L1", "L2", "L3", "L4", "L5", "L6", "R1", 
"R2", "R3", "R4", "R5", "R6"), class = "factor"), WearRate = c(-0.000367, 
0, 0, 0, 0.001888, 0, -0.00018, 0.000579, -0.000211, 0.000643, 
0.000106, 0, 0, 0, 0.000833, 0, -0.00036, 0.000811, -0.000819, 
0.002044, -0.00029, 0, 0, 0, 0.001666, 0, -0.000348, 0.000888, 
-0.000679, 0.001636, 8.7e-05, 0, 0, 0, 0.000666, 0, -0.000315, 
0.000618, -0.000585, 0.001636, -0.000512, 0, 0, 0, 0.002499, 
0, -0.000247, 0.000734, -9.4e-05, 0.000409)), .Names = c("Date", 
"Wheel", "WearRate"), row.names = 211269:211318, class = "data.frame")

我正在尝试绘制Date vs WearRatecolor by Wheel 的情节。代码如下:

ggplot(data = df) + geom_point(mapping = aes(x = Date, y = WearRate, color = Wheel))

它有效,但我想放置实际的日期标签。我该怎么做?

编辑

情节目前看起来如下所示。但是,我想在 X 轴上看到“2015 年 8 月”、“2015 年 9 月”等,我想显示所有的刻度。

【问题讨论】:

    标签: r ggplot2 machine-learning data-visualization


    【解决方案1】:
    ggplot(data = df) + 
      geom_point(mapping = aes(x = Date, y = WearRate, color = Wheel))+
      scale_x_date(date_labels="%b %Y", breaks = unique(df$Date))
    

    【讨论】:

    • 我遇到了和你一样的问题。您可能已经找到了解决方案,但在这里我想与正在寻找它的其他人分享。它适用于我的情况。我希望它也对你有用。
    • 我认为您还可以解释为什么 unique() 实际工作以及它与接受的答案有何不同
    • 感谢您的建议。 unique(0) 仅显示数据存在的日期。
    【解决方案2】:

    最简单的方法是使用scale_x_date

    ggplot(data = df) + 
      geom_point(mapping = aes(x = Date, y = WearRate, color = Wheel))+
      scale_x_date(date_labels="%b %y",date_breaks  ="1 month")
    

    %b: 缩写月份名称
    %y: 没有世纪的年份
    有关全部可能性的描述,请参阅?strftime()

    【讨论】:

    • 这可行,但它只显示 3 个刻度。我想显示所有的刻度。
    • 我现在每个月都显示。 Lmk 如果应该是这样的话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多