【问题标题】:ggplot 2 - Change legend categories with numeric values (no factors)ggplot 2 - 使用数值更改图例类别(无因子)
【发布时间】:2014-04-29 16:58:17
【问题描述】:

假设我使用 mtcars 数据集。我想根据重量(wt)设置点的大小。如果我按如下所示执行此操作,R/ggplot2 将为我提供一个具有 4 个类别(2、3、4、5)的图例。

library(ggplot2)
mtc <- mtcars
p1 <- ggplot(mtc, aes(x = hp, y = mpg))
p1 <- p1 + geom_point(aes(size = wt))     
print(p1)

如何更改图例的比例/名称/类别。如果“类别”是因素,我找到了有关如何执行此操作的信息,但我不知道如何使用数值执行此操作。我需要将它们保持为数字,否则它不再适用于点的大小。

我的真实数据集有大约 100 个 wt 值(从 1 到 150 的所有值),我想保留 5 个值。 (ggplot 2 给我 2 -> 50 和 100)

1) 如何更改该图例的比例?例如,在 mtc 示例中,我只想要 2 个大小为 2 和 5 的点

2) 我正在考虑制作以下类别:

mtc$wtCat[which(mtc$wt<=2)]=1
mtc$wtCat[which(mtc$wt>2 & mtc$wt<=3)]=2
mtc$wtCat[which(mtc$wt>3)]=3

p1 <- ggplot(mtc, aes(x = hp, y = mpg))
p2 <- p1 + geom_point(aes(size = wtCat), stat="identity")     
print(p2)

然后将图例中的 1、2、3 重命名为 3,但我也不知道该怎么做。

非常感谢。

【问题讨论】:

    标签: r ggplot2 legend numeric


    【解决方案1】:

    您可以使用scale_size_continuous() 并使用参数breaks= 设置您希望在图例中看到的级别,并使用参数labels= 更改图例条目的标记方式。

    ggplot(mtcars,aes(hp,mpg,size=wt))+geom_point()+
      scale_size_continuous(breaks=c(2,5),labels=c("<=2",">2"))
    

    【讨论】:

    • 这正是我想要的。
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多