本文介绍了用ggplot2中定义为时间序列的X轴绘制条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3列的小标题,分别代表3个不同变量(a,b,c)的观测日期.

I have a tibble with 3 columns, representing the date of observations of 3 different variables (a, b, c).

我想使用ggplo2绘制条形图,其中X轴表示时间.我希望独立于数据的时间跨度,X轴始终代表整个月份(例如,从第1天到第31天).

I want to depict a bar plot using ggplo2, in which the X-axis represents the time. Independently on the time-span of my data, I want the X-axis to represent always the whole month (from day 1 to day 31, let's say).

test <- tibble(date=c("1/1/1","1/1/1","2/1/1","2/1/1","2/1/1","5/1/1","5/1/1","5/1/1"),
            variable=c("a","b","a","b","c","a","b","c"),
            observation=c(0.4,0.6,0.3,0.3,0.4,0.2,0.5,0.3))

ggplot(test, aes(x=as.Date(date), y=observation, fill=variable)) +
    geom_bar(position = "stack", stat = "identity") +
    scale_x_date(date_breaks = "1 day",
                 labels = date_format("%d/%m/%Y")) +
theme(text = element_text(size=6),
      axis.text.x = element_text(angle=90, hjust=1))

但是,我无法读取所得绘图中的X轴信息.我是否应该使用其他函数代替scale_x_date来定义我的X轴?

However, I can not read the X-axis information in my resulting plot. Should I use other functions instead of scale_x_date to define my X-axis?

推荐答案

您需要在 as.Date()中使用选项 format = ,以便使可以将5/1/1 读为2001年1月5日(按预期),而不是2005年1月1日(目前正在翻译).

You need to use the option format= within as.Date() so that 5/1/1 can be read as January 5th, 2001 (as intended) instead of January 1st, 2005 (as is currently hapening).

tibble(
    date =
        c(
            "1/1/1", "1/1/1", "2/1/1", "2/1/1",
            "2/1/1", "5/1/1", "5/1/1", "5/1/1"
        ) %>%
        as.Date(format = "%d/%m/%y"),
    variable = c("a", "b", "a", "b", "c", "a", "b", "c"),
    observation = c(0.4, 0.6, 0.3, 0.3, 0.4, 0.2, 0.5, 0.3)
) %>%
    ggplot(aes(x = date, y = observation, fill = variable)) +
    geom_bar(position = "stack", stat = "identity") +
    scale_x_date(
        date_breaks = "1 day",
        labels = date_format("%d/%m/%Y")
    ) +
    theme(
        text = element_text(size = 6),
        axis.text.x = element_text(angle = 90, hjust = 1)
    )

注意,我在 tibble()中使用了 as.Date(...,format =%d/%m/%y"),以便图例变得更少污染了.

Notice I use as.Date(..., format = "%d/%m/%y") within your tibble() so that the legend becomes less poluted.

这篇关于用ggplot2中定义为时间序列的X轴绘制条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:30