【问题标题】:How to plot the graph using all the dates in x axis using R?如何使用 R 使用 x 轴上的所有日期绘制图表?
【发布时间】:2020-04-10 09:42:11
【问题描述】:

我正在使用数据

Date of acquisition Bperp(m)
29/01/2020  0.00 
10/02/2020  -23.22 
22/02/2020  15.03 
17/01/2020  8.85 
30/12/2019  -26.13 
06/12/2019  7.35 
18/12/2019  -31.04 
11/01/2020  19.40 
23/01/2020  12.44 
16/02/2020  -25.21 
04/02/2020  -6.45 
28/02/2020  70.35 

我需要将以上数据绘制成

Target graph

这是我使用的代码

library(tidyverse)
library(readxl)


data <- readxl::read_excel("Sentinel-1 Metadata info.xls")
centroid <- slice(data,1)

data %>% 
  ggplot(aes(`Date of acquisition`, `Bperp(m)`)) +
  geom_point() +
  geom_segment(aes(x = centroid$`Date of acquisition`, y = centroid$`Bperp(m)`, 
                   xend = `Date of acquisition`, yend = `Bperp(m)`)) +
  theme_minimal()

I got the graph like this

但我想以 DDMMYYYY 格式显示所有日期。

怎么做?

Formatting dates on X axis in ggplot2 的讨论并没有解决我的问题。

【问题讨论】:

  • centroid$'Date of acquisition' 中的数据是“日期”因素吗?请与str(centroid) 联系。日期很复杂,所以像lubridate 这样的包会有所帮助。有关信息,请参阅该文档,但您需要在 x 轴上指定日期格式,为此,您的 centroid$'Date of acquisition' 必须指定为类 Date。就像您提到的链接帖子一样,要在轴上格式化日期,您应该使用scale_x_Date(labels=date_format(...))。在帖子和 lubridate 链接中有特定的语法。
  • 是的,它是日期格式,我在这里添加了数据
  • 你能把dput(data)的结果加进去吗?它输出可以轻松复制/粘贴到 R 中的格式化文本,以直接重新创建您的 data.frame。
  • 结构(列表(Date of acquisition =结构(C(1580256000,1581292800,1582329600,1579219200,1577664000,1575590400,1576627200,1578700800,1579737600,1581811200,1580774400,1582848000),class= C(” POSIXct", "POSIXt"), tzone = "UTC"), Bperp(m) = c(0, -23.22, 15.03, 8.85, -26.13, 7.35, -31.04, 19.4, 12.44, -25.21, -6.45, 70.35) ), row.names = c(NA, -12L), class= c("tbl_df", "tbl", "data.frame"))

标签: r date ggplot2 axis-labels


【解决方案1】:

您可以使用scale_x_Date 随意格式化您的轴,并通过label=format_date(format=...) 指定标签格式。为此,您需要先将“获取日期”列转换为class Date,而不是class POSIXct, POSIXt。这些是其他日期格式,但 ggplot 似乎不喜欢它,除非我强制它为 Date

特别说明: 我还删除了原始数据标题和括号中的空格,因为这样做是不好的做法,因为那里的语法会干扰语法在你的代码中。之后您可以随时更改绘图中的命名并调用您的数据清理器。此外,最好不要在 ggplot 函数中使用 data.frame$variable 调用,除非在数据帧之间进行绘图,否则您应该只指定变量名称(而不是引号)以保持美观。您将在下面看到我是如何在您的情况下做到这一点的,您的数据来自数据框和质心。

# your data frame here is called `df`.  Just my preference.
# 'Date of acquisition` was changed to be `Date_of_acquisition`
# 'Bperp(m)' was changed to 'Bperpm'

df$Date_of_acquisition <- as.Date(df$Date_of_acquisition)  # change to Date
centroid <- slice(df, 1)

ggplot(df, aes(Date_of_acquisition, Bperpm)) + geom_point() +
    geom_segment(aes(
        x = centroid$Date_of_acquisition, y = centroid$Bperpm,
        xend = Date_of_acquisition, yend = Bperpm)) +
    theme_minimal() + 
    scale_x_date(labels=date_format(format="%d-%m-%Y"))  # change format here

剧情如下:

【讨论】:

    猜你喜欢
    • 2011-08-02
    • 1970-01-01
    • 2011-03-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2012-03-26
    相关资源
    最近更新 更多