【问题标题】:ggplot2 point size by numeric: Do not display point when value = 0ggplot2点大小按数字:值= 0时不显示点
【发布时间】:2019-08-11 06:03:38
【问题描述】:

我有两个时间序列的数据,我想一起绘制。 x 轴将是日期,y 轴将是系列 1 的折线图,而点大小将根据系列 2 的数值进行缩放。但是,当系列 2 = 0 时,我希望 ggplot根本不显示一个点。我尝试将点大小的范围从最小值设置为 0,但它仍然显示值为 0 的点。

重现问题的代码如下:

Dates = c("2015-05-01", "2015-05-02", "2015-05-03", "2015-05-04", "2015-05-05", "2015-05-06")
Dates = as.Date(Dates)
Series1 = c(0,2,8,5,3,1)
Series2 = c(0,0,5,0,10,5)

df = data.frame(Dates, Series1, Series2)
ggplot(data = df)+
   geom_line(aes(x=Dates, y = Series1))+
   geom_point(aes(x=Dates, y = Series1, size = Series2))+
   scale_size_continuous(range = c(0, 5))

这会产生以下图表:

如何让 ggplot2 在 Series2 = 0 时不创建点,但仍显示线? 我还尝试将 Series2 的 0 替换为 NA,但这会导致绘图失败。

【问题讨论】:

  • 也许您和我查看或保存此内容的方式有所不同,因为使用您的代码,我有大小为 0 的点未显示。不知道为什么它们看起来不一样;也许不同的分辨率?但是数据viz nerds会争辩说你应该scale to area, not radius,这就是为什么scale_size_area只需要一个最大尺寸才能将0个值放在0尺寸上

标签: r ggplot2


【解决方案1】:

您可以将最小值更改为负值:

ggplot(data = df) +
  geom_line(aes(x = Dates, y = Series1))+
  geom_point(aes(x = Dates, y = Series1, size = Series2))+
  scale_size_continuous(range = c(-1, 5)) 

如果您不希望图例包含 0,您可以添加 breaks

scale_size_continuous(range = c(-1, 5), breaks = seq(2.5, 10, 2.5)) 

【讨论】:

    【解决方案2】:

    另一种选择是利用alpha 使size == 0 点不可见。我们将aes中的alpha设置为逻辑表达式Series2 == 0,然后使用scale_alpha_manual将值设置为1如果FALSE和0(不可见)如果TRUE

    ggplot(data = df)+
        geom_line(aes(x=Dates, y = Series1))+
        geom_point(aes(x=Dates, y = Series1, size = Series2, alpha = Series2 == 0))+
        scale_size_continuous(range = c(1, 5)) +
        scale_alpha_manual(values = c(1,0)) +
        guides(alpha = FALSE)     # Hide the legend for alpha
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 2016-02-09
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多