首页 文章

如何在ggplot中对轴标签进行分层?

提问于
浏览
1

我的数据采用以下结构:

month <- c("May", "June", "July", "May", "June", "July")
year <- c("2015", "2015", "2015", "2016", "2016", "2016")
value <- c(1:3, 3:1)
df <- data.frame(month, year, value)

(这两年的数据实际上从1月到12月一直持续,这只是一个简短的可重复的例子 . )

我正在使用ggplot进行 value 的时间序列图(假设我不能使用 plot.ts() ,原因太复杂,无法在此解释) . 如何对x轴的标签进行分层,这样每个刻度标记都标有月份,但是在下面标有下面那个带有年份的标签,所以我得到类似的东西:

-------+-------+-------+----//---+-------+-------+-----
      May     June    July      May     June    July
              2015                      2016

2 回答

  • 4

    我不会制作两个轴而只是一个,调整后的标签带有换行符 . 该示例显示了如何在每月下面添加年份 . 我习惯只把年份放在1月以下,如果januari不是第一个月的年份 . 您可以根据自己的喜好调整标签的准备工作 .

    df$lab <- factor(1:6, labels = paste0(month,"\n",year))
    ggplot(df, aes(x = lab, y = value)) + geom_point()
    

    enter image description here

  • 2

    另一种选择是按年使用刻面并将刻面标签放在x轴标签下方 . 这使得每年只有一年的标签更容易 . 我已经删除了面板之间的空间,以创建一个无面的情节的外观,但在年份之间添加了一条垂直线以突出显示时间的中断 . 如果您更喜欢单独的面板,则只需删除 panel.spacingpanel.border theme 元素 .

    theme_set(theme_classic())
    
    df$month = factor(df$month, levels=month.name)
    
    ggplot(df, aes(x = month, y = value)) + 
      geom_point() +
      facet_grid(. ~ year, switch="x") +
      theme(strip.placement="outside",
            strip.background=element_rect(colour=NA),
            panel.spacing.x=unit(0,"lines"),
            panel.border=element_rect(colour="grey50", fill=NA))
    

    enter image description here

    根据您的使用情况,您可能会发现每年最好使用颜色美学并将所有线条放在一个面板上:

    ggplot(df, aes(x = month, y = value, colour=year, group=year)) + 
      geom_line() + geom_point()
    

    enter image description here

相关问题