【问题标题】:ggplot: How to increase space between axis labels for categorical data?ggplot:如何增加分类数据的轴标签之间的空间?
【发布时间】:2016-10-26 14:08:30
【问题描述】:

我喜欢 ggplot,但很难自定义一些元素,例如 X 轴标签和网格线。问题的标题说明了一切,但这里有一个可重复的示例:

可重现的例子

library(ggplot2)
library(dplyr)

# Make a dataset
set.seed(123)
x1 <- c('2015_46','2015_47','2015_48','2015_49'
        ,'2015_50','2015_51','2015_52','2016_01',
        '2016_02','2016_03')
y1 <- runif(10,0.0,1.0)
y2 <- runif(10,0.5,2.0)


# Make the dataset ggplot friendly
df_wide <- data.table(x1, y1, y2)
df_long <- melt(df_wide, id = 'x1')

# Plot it
p <- ggplot(df_long, aes(x=x1, 
                         y=value, 
                         group=variable, 
                         colour=variable )) + geom_line(size=1)
plot(p)

# Now, plot the same thing with the same lines and numbers,
# but with increased space between x-axis labels
# and / or space between x-axis grid lines.

情节1

情节看起来像这样,在当前的形式下看起来还不错:

情节2

当数据集变大时会出现问题,并且 x 轴上的标签开始相互重叠,如下所示:

到目前为止我所做的尝试:

我已经按照here 的建议使用 scale_x_discrete 进行了几次尝试,但到目前为止我还没有运气。真正让我烦恼的是,我不久前看到了一些关于这些事情的教程,但尽管进行了两天的激烈谷歌搜索,我还是找不到它。当我尝试新事物时,我将更新此部分。 我期待您的建议!

【问题讨论】:

  • +theme(axis.text.x = element_text(angle=90, vjust=0.5, size=10)) 应该有助于阅读。
  • 如果这些是年份和周数,您可能希望使用 scale_date 代替。例如,这将允许您每年设置休息时间。
  • 如果您将 x 值转换为有效日期,ggplot 将获得一个不错的时间轴。目前这些是字符串
  • 一年中一周的有效日期格式是什么?

标签: r ggplot2


【解决方案1】:

如上所述,假设 x1 代表 year_day,ggplot 为日期刻度提供了合理的默认值。

首先将 x1 转换为有效的日期格式,然后按照您的方式绘制:

df_long$x1 <- strptime(as.character(df_long$x1), format="%Y_%j")

ggplot(df_long, aes(x=x1, y=value, group=variable, colour=variable)) +
    geom_line(size=1)

由于时间序列不连贯,该图看起来有点奇怪,但scales_x_date() 提供了一种自定义轴的简单方法: http://docs.ggplot2.org/current/scale_date.html

【讨论】: