【问题标题】:ggplot2 geom_count set legend breaks to integersggplot2 geom_count 将图例中断设置为整数
【发布时间】:2017-08-28 14:47:49
【问题描述】:

我想使用 ggplot2 中的 geom_count 图,但值的范围太小,图例中断成为发生次数的浮点数,例如1 1.5 2 2.5 3

这是一个测试用例:

test = mtcars[1:6,]

ggplot(test, aes(cyl, carb)) +
  geom_count(aes(color = ..n.., size = ..n..)) +
  guides(color = 'legend')

我怎样才能使中断只发生在完整整数处?

【问题讨论】:

    标签: r ggplot2 count legend


    【解决方案1】:

    您可以为连续的colorsize 刻度设置breaks

    您可以为中断提供一个值向量,但根据文档,也可以提供 breaks 参数:

    一个将限制作为输入并返回中断作为输出的函数

    因此,对于像您的示例这样的简单案例,您可以使用 as.integerround 作为函数。

    ggplot(test, aes(cyl, carb)) +
         geom_count(aes(color = ..n.., size = ..n..)) +
         guides(color = 'legend') +
         scale_color_continuous(breaks = round) +
         scale_size_continuous(breaks = round)
    

    对于比您的示例更大的整数范围,您可以手动输入分隔符,例如 breaks = 1:3,或者编写一个函数来获取刻度的限制并返回一个整数序列。然后您可以将此函数用于breaks

    可能看起来像:

    set_breaks = function(limits) {
         seq(limits[1], limits[2], by = 1)
    }
    
    ggplot(test, aes(cyl, carb)) +
         geom_count(aes(color = ..n.., size = ..n..)) +
         guides(color = 'legend') +
         scale_color_continuous(breaks = set_breaks) +
         scale_size_continuous(breaks = set_breaks)
    

    【讨论】:

    • 感谢使用矢量,但是当我使用round 时,我失去了价值?这是一个测试用例test = data.frame(cyl=c(rep(4,3),rep(2,2),1), carb=c(rep(6,3),rep(2,2),5)),其中使用 break = round 会导致在 1 和 3 而不是 1、2、3 处中断
    • 这是我唯一看到一个实际示例的地方,该示例说明了“将限制作为输入并返回中断作为输出的函数”的确切含义。谢谢!
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2018-02-03
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-28
    相关资源
    最近更新 更多