【问题标题】:How to create a line chart in R with x axis labels that are dates from table data?如何在 R 中使用来自表数据的日期的 x 轴标签创建折线图?
【发布时间】:2018-10-23 18:57:56
【问题描述】:

我有一个大型数据集,其中包含在不同日期进行的观察。我想在 R 中可视化基于观察月份的观察频率。我用表格来计算每个日期的行数:

freq_by_month <- c(table(format(dataframe_name$Date_Collected,"%Y-%m")))

现在我想创建一个显示这些数据点随时间变化的折线图,并用收集日期标记这些点。

我尝试过使用

plot(freq_by_month, type="o", xlab="Date", ylab="a y label goes here")

这给了我一个带有数字 x 轴标签的图表。

我也试过

plot(freq_by_month, type="o", xaxt="n", xlab="Date", ylab="a y label goes here")
axis(1, at=1:34, labels=TRUE)

这只会产生一个数字间隔较小的图表。我想我需要将标签设置为矢量或其他东西,但我不确定如何从表格中执行此操作。我不想手动执行此操作,因为我每个月都会添加新的数据点。

供参考,

str(freq_by_month)
 Named int [1:34] 1 1 9 1 3 4 2 1 1 3 ...
 - attr(*, "names")= chr [1:34] "2012-03" "2015-06" "2015-07" "2015-08"
 head(freq_by_month)
2012-03 2015-06 2015-07 2015-08 2016-01 2016-02 
      1       1       9       1       3       4 

如果我完全倒退,而且我不应该首先使用表格来计算数据,我也会很高兴知道这一点。

【问题讨论】:

  • 第一个链接显示了如何创建连续日期的向量,在这种情况下不相关。不过,知道如何从表中的行创建向量可能是一种解决方案。第二个链接与顺序/随机数据有类似的问题,因此不适用。第三个链接用于条形图,它会生成带有正确标签的图并且没有相同的问题。它还建议手动创建一个向量(这对于大型数据集来说会很乏味,并且每个月都会发生变化),并且用于连续日期,这也是无关紧要的。最后一个链接也有类似的问题。

标签: r time-series data-visualization


【解决方案1】:

这就是我最终解决这个问题的方法。

df<-read.xlsx("data set file.xlsx",1, header=TRUE, fill=TRUE) 
 #Import the data ("name of file", sheet number, etc.)

str(df)
'data.frame':   911 obs. of  16 variables:
 $ Date: Date, format: "2012-03-23" "2015-06-15" ...
 $ Col2: chr  "lorem" "ipsum" ...
 $ Col3: chr  "lorem" "ipsum" .... #etc.

df$Month <-as.Date(cut(df$date, breaks="month") 
 #adds a column ("Month") with the Date rounded down 
 #to the first of each month 

df2 <-df %>%
  group_by(Month) %>%
  summarise(date_column_name=n()) #summarizes the number of 
                                  #observations by month

str(df2)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   34 obs. of  2 
variables:
$ Month    : Date, format: "2012-03-01" "2015-06-01" ...
$ Summarized_Column: int  1 1 9 1 3 4 2 1 1 3 ...

df3 = as.data.frame(df2) #Converts df2 to a data frame.

#all the prettiness for plotting:
ggplot(df3, aes(x=Month, y=Date, color=(Month))) + 
  geom_point()+
  labs(title="Title", x="", y="Y Axis Title") +
  ylim(c(0,1000))+
  scale_x_date(date_breaks = "4 months", date_labels= "%b-%y") +
  theme_classic() +
  theme(axis.text.x = element_text(angle = 60, vjust=1, hjust = 1), #rotates labels and shift location
    panel.background = element_rect(fill="gray97", colour="black"),
    axis.text=element_text(size=11),
    axis.title = element_text(size=13),
    plot.title = element_text(hjust = 0.5))

Output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 2021-06-19
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    相关资源
    最近更新 更多