简体   繁体   English

ggplot:如何增加分类数据的轴标签之间的空间?

[英]ggplot: How to increase space between axis labels for categorical data?

I love ggplot, but find it hard to customize some elements such as X axis labels and grid lines.我喜欢 ggplot,但发现很难自定义一些元素,例如 X 轴标签和网格线。 The title of the question says it all, but here's a reproducible example to go with it:问题的标题说明了一切,但这里有一个可重复的示例:

Reproducible example可重现的例子

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.

Plot1情节 1

The plot looks like this, and doesn't look too bad in it's current form:情节看起来像这样,并且在当前形式下看起来还不错: 在此处输入图片说明

Plot2情节2

The problem occurs when the dataset gets bigger, and the labels on the x-axis start overlapping each other like this:当数据集变大时会出现问题,并且 x 轴上的标签开始相互重叠,如下所示: 在此处输入图片说明

What I've tried so far:到目前为止我尝试过的:

I've made several attempts using scale_x_discrete as suggested here , but I've had no luck so far.我已经按照此处的建议使用 scale_x_discrete 进行了几次尝试,但到目前为止我都没有运气。 What really bugs me is that I saw some tutorial about these things a while back, but despite two days of intense googling I just can't find it.真正让我烦恼的是,我不久前看到了一些关于这些东西的教程,但尽管我用了两天的谷歌搜索,我还是找不到它。 I'm going to update this section when I try new things.当我尝试新事物时,我将更新此部分。 I'm looking forward to your suggestions!我期待着您的建议!

As mentioned above, assuming that x1 represents a year_day, ggplot provides sensible defaults for date scales.如上所述,假设 x1 代表 year_day, ggplot为日期刻度提供合理的默认值。

First make x1 into a valid date format, then plot as you already did:首先将 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)

The plot looks a little odd because of the disconnected time series, but scales_x_date() provides an easy way to customize the axis: http://docs.ggplot2.org/current/scale_date.html由于断开的时间序列,该图看起来有点奇怪,但scales_x_date()提供了一种自定义轴的简单方法: http : scales_x_date()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM