【问题标题】:In R, force x-axis ticks to label each bin in my ggplot (geom_col) [duplicate]在R中,强制x轴刻度标记我的ggplot(geom_col)中的每个bin [重复]
【发布时间】:2021-11-23 12:26:57
【问题描述】:

背景

这可能是一个重复的问题,但我已经浏览了几篇帖子,并没有找到我正在寻找的确切内容。我有一个很好的ggplot 我用geom_col 制作的:

它来自一个看起来像这样的df

我使用以下代码实现了它:

ggplot(data = avg_repeats_per_year, aes(x = year, y = ratio)) +
  geom_col()

您可以看到ratio 中的每个数字对应于从 2009 年到 2018 年的不同 year(有一个 NA 年份)。

问题

您可以看到每个条形对应于year 中的一年,但实际上图的 x 轴上只标记了 3 年。

如何让每个条形图都有一个对应年份的标签?

我的尝试

我做过这样的尝试:

ggplot(data = avg_repeats_per_year, aes(x = year, y = ratio)) +
  geom_col() + 
  scale_x_discrete(breaks = avg_repeats_per_year$year, labels = avg_repeats_per_year$year)

但是什么都没有出现。有什么想法吗?

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    它似乎是数字列,将其更改为 factorcharacter 应该可以工作

    ggplot(data = avg_repeats_per_year, aes(x = factor(year), y = ratio)) +
        geom_col() + 
        scale_x_discrete(labels = avg_repeats_per_year$year) + 
        xlab("year")
    

    -输出

    数据

    avg_repeats_per_year <- structure(list(year = c(2009L, 2010L, 2011L, 2012L, 2013L, 2014L, 
    2015L, 2016L, 2017L, 2018L, NA), ratio = c(2.28, 2.24, 2.3, 2.45, 
    2.32, 2.41, 2.56, 2.52, 2.63, 1.32, 0.56)), class = "data.frame", row.names = c(NA, 
    -11L))
    

    【讨论】:

    • 抱歉,刚回办公室。我现在就试试这个并报告。
    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2013-12-30
    相关资源
    最近更新 更多