【问题标题】:Plot multiple lines with a character as x-axis以字符为 x 轴绘制多条线
【发布时间】:2016-10-17 11:07:45
【问题描述】:

我有一个跨越数年的每日时间序列。我想在同一个 graf 上为每一年绘制一个情节。

所以,我有一年中的所有日期,格式为 %m-%d,每年都有一个点。

数据示例:

require(dplyr)
require(ggplot2)

df <- data.frame(Date = seq.Date(from = as.Date("2013-01-01"), 
                                 to = as.Date("2016-10-01"), by = "day"), 
                 xv = rnorm(1370))

# First I add my x-axis (Days) and my factor variable (Year)
df <- df %>% mutate(Year = format(Date, "%Y"), 
                    Days = format(Date, "%m-%d")) %>% select(Date, Year, Days, xv)

基本上它应该像这样排序:(除了年份不应该在 x 轴上)

现在,我可以轻松地绘制多面图,但这包含下一年的空白空间,这是我不想要的,而且我也非常希望同一图表上的所有线。

# Wrong faceted graph
ggplot(df, aes(x = Date, y = xv, group = Year, colour = Year)) + 
  geom_line() +
  facet_grid(.~Year)

我尝试了设置 group = 1 的变体,因此您可以使用字符/因子作为 x 变量进行绘图,但是您不能绘制超过一条线。数据可能包含缺失的变量或不完整的日期(闰年等)。我真的更喜欢 ggplot 解决方案。

【问题讨论】:

  • 为什么不使用你创建的变量Daysggplot(df, aes(x = Days, y = xv, group = Year, colour = Year)) + geom_line()
  • 我试过了...不知道为什么我不能让它工作!
  • 还是不行吗?它似乎对我很好。

标签: r plot ggplot2


【解决方案1】:

您可以将facet_wrapscales = 'free_x' 结合使用:

ggplot(df, aes(x = Date, y = xv, group = Year, colour = Year)) + 
  geom_line() +
  facet_wrap(~Year, scales = 'free_x')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多