如何在ggplot轴上不显示所有标签?

Dro*_*ide 22 r ggplot2

我正在尝试使用ggplot2这个来绘制:在此输入图像描述但正如你在x轴上看到的,你无法阅读任何东西......

那么我怎样才能在x轴上显示每10年的值呢?

这是我的命令:

ggplot(prova, aes(x=year, y=mass..g.)) + geom_line(aes(group = 1))

use*_*412 23

您的year列是否为数字?您可以scale_x_continuous使用breaks参数添加以指定x轴刻度的位置.我无法分辨图像中的年份范围,但如果它是从1900年到2000年(例如),你可以做这样的事情:

ggplot(prova, aes(x=year, y=mass..g.)) +
    geom_line(aes(group=1)) +
    scale_x_continuous(breaks=seq(1900, 2000, 10))
Run Code Online (Sandbox Code Playgroud)


Gre*_*gor 16

假数据:

df = data.frame(year = as.factor(1800:2000),
                variable = rnorm(length(1800:2000)))
Run Code Online (Sandbox Code Playgroud)

你的假数据图:

ggplot(df, aes(x = year, y = variable, group = 1)) +
    geom_line()
Run Code Online (Sandbox Code Playgroud)

问题是你的年变量是factor(或者可能是一个字符串?),所以它被解释为分类.您可以在此框架内工作:

ggplot(df, aes(x = year, y = variable, group = 1)) +
    geom_line() +
    scale_x_discrete(breaks = levels(df$year)[c(T, rep(F, 9))])
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,您可以将其转换为数字并自动运行:

df$real_year = as.numeric(as.character(df$year))
ggplot(df, aes(x = real_year, y = variable)) +
    geom_line()
Run Code Online (Sandbox Code Playgroud)

请注意,这样做,"正确的方式",你不必打扰group = 1或搞乱规模.ggplot奖励您以适当的格式获取数据:修复您的数据,您无需修复您的情节.如果你想确保标签每10年一次,你可以scale_x_continuous按照用户2034412的建议使用,但默认情况下它会很好地猜测轴上的"漂亮"断点.

如果您的x轴是实际日期或日期时间,1984-10-31那么您应该将其转换为Date对象(或者POSIX如果它也有时间也可以转换为对象),然后再次ggplot知道如何正确处理它.请参阅?strftime(基本功能)或lubridate包以转换为适当的日期类.


ren*_*nsa 8

其他答案涵盖了您的日期是数字年份的情况,但如果(如@Gregor所说)您的日期是实际Date对象,则更容易:

scale_x_date(name = 'My date axis title', date_breaks = '20 years',
        date_labels = '%Y')
Run Code Online (Sandbox Code Playgroud)

有了scale_date,您可以使用直观的语言控制休息,并使用(希望)熟悉的strptime符号标记.