【问题标题】:R ggplot and facet grid: how to control x-axis breaksR ggplot 和 facet grid:如何控制 x 轴中断
【发布时间】:2012-01-21 07:27:44
【问题描述】:

我正在尝试使用 ggplot 绘制每个日历年的时间序列变化,但我在 x 轴的精细控制方面遇到了问题。如果我不使用scale="free_x",那么我最终会得到一个 x 轴,显示几年以及相关年份,如下所示:

如果我确实使用了scale="free_x",那么正如人们所期望的那样,我最终会为每个图提供刻度标签,并且在某些情况下会因图而异,这是我不想要的:

我已经多次尝试使用 scale_x_date 等来定义 x 轴,但没有任何成功。因此,我的问题是:

问。如何控制 ggplot 构面网格上的 x 轴中断和标签,以便(时间序列)x 轴对于每个构面都是相同的,仅显示在面板底部,并且格式为月份格式 1, 2、3 等或“一月”、“二月”、“三月”?

代码如下:

require(lubridate)
require(ggplot2)
require(plyr)

# generate data
df <- data.frame(date=seq(as.Date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200))
# remove weekend days
df <- df[!(weekdays(as.Date(df$date)) %in% c('Saturday','Sunday')),]
# add some columns for later
df$year <- as.numeric(format(as.Date(df$date), format="%Y"))
df$month <- as.numeric(format(as.Date(df$date), format="%m"))
df$day <- as.numeric(format(as.Date(df$date), format="%d"))

# calculate change in price since the start of the calendar year
df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))

p <- ggplot(df, aes(date, pctchg)) +
  geom_line( aes(group = 1, colour = pctchg),size=0.75) + 
  facet_wrap( ~ year, ncol = 2,scale="free_x") +
  scale_y_continuous(formatter = "percent") +
  opts(legend.position = "none")

print(p)

【问题讨论】:

    标签: r ggplot2 plyr


    【解决方案1】:

    这是一个例子:

    df <- transform(df, doy = as.Date(paste(2000, month, day, sep="/")))
    
    p <- ggplot(df, aes(doy, pctchg)) +
     geom_line( aes(group = 1, colour = pctchg),size=0.75) + 
     facet_wrap( ~ year, ncol = 2) +
     scale_x_date(format = "%b") +
     scale_y_continuous(formatter = "percent") +
     opts(legend.position = "none")
    p
    

    你想要这个吗?

    诀窍是生成同一虚拟年份的一年中的某天

    更新

    这里是开发版本的示例(即 ggplot2 0.9)

    p <- ggplot(df, aes(doy, pctchg)) +
      geom_line( aes(group = 1, colour = pctchg), size=0.75) + 
      facet_wrap( ~ year, ncol = 2) +
      scale_x_date(label = date_format("%b"), breaks = seq(min(df$doy), max(df$doy), "month")) +
      scale_y_continuous(label = percent_format()) +
      opts(legend.position = "none")
    p
    

    【讨论】:

    • Sasu ga kohske。当您考虑它时,它既简单又合乎逻辑,并且它与我的数据配合得很好。我是否还可以问是否有任何(直接的方法可以使休息时间和标签从一月到十二月而不是从一月到一月,如您上面的屏幕截图所示?我可以忍受一月到一月,只是想知道是否有解决方法。谢谢丹
    • Arigatou gozaimasu。在当前版本中,这可能并不容易。
    • 很有趣,但看起来也完全不同,例如格式化程序替换 percent_format() 函数。希望向后兼容!
    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2021-07-05
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多