【问题标题】:Visualizing the difference between two points with ggplot2用 ggplot2 可视化两点之间的差异
【发布时间】:2016-10-28 15:39:55
【问题描述】:

我想在 ggplot2 中用一条线/条可视化两点之间的差异。

假设我们有一些关于收入和支出的时间序列数据。 我们不仅要可视化它们,还要可视化余额(=收入 - 支出)。 此外,我们想指出余额是正数(=盈余)还是负数(=赤字)。

我尝试了几种方法,但都没有产生令人满意的结果。这里我们举一个可重现的例子。

# Load libraries and create LONG data example data.frame
library(dplyr)
library(ggplot2)
library(tidyr)

df <- data.frame(year  = rep(2000:2009, times=3),
                 var   = rep(c("income","spending","balance"), each=10),
                 value = c(0:9, 9:0, rep(c("deficit","surplus"), each=5)))
df

1. 使用 LONG 数据的方法

不出所料,它不适用于 LONG 数据, 因为geom_linerange 参数yminymax 无法正确指定。 ymin=value, ymax=value 绝对是错误的方式(预期的行为)。 ymin=income, ymax=spending 显然也是错误的(预期行为)。

df %>% 
ggplot() + 
  geom_point(aes(x=year, y=value, colour=var)) +
  geom_linerange(aes(x=year, ymin=value, ymax=value, colour=net))

#>Error in function_list[[i]](value) : could not find function "spread"

2.WIDE 数据方法

我几乎可以使用 WIDE 数据了。 情节看起来不错,但缺少 geom_point(s) 的图例(预期行为)。 简单地将show.legend = TRUE 添加到两个geom_point(s) 并不能解决问题,因为它会叠印geom_linerange 图例。此外,我宁愿将 geom_point 代码行合并为一个(参见 1.Approach)。

df %>% 
  spread(var, value) %>% 
ggplot() + 
  geom_linerange(aes(x=year, ymin=spending, ymax=income, colour=balance)) +
  geom_point(aes(x=year, y=spending), colour="red", size=3) +
  geom_point(aes(x=year, y=income), colour="green", size=3) +
  ggtitle("income (green) - spending (red) = balance")

3.使用 LONG 和 WIDE 数据的方法

将 1.Approach 与 2.Approach 结合会导致另一个不令人满意的情节。图例没有区分 balance 和 var(=预期行为)。

ggplot() + 
  geom_point(data=(df %>% filter(var=="income" | var=="spending")),
             aes(x=year, y=value, colour=var)) +
  geom_linerange(data=(df %>% spread(var, value)), 
                 aes(x=year, ymin=spending, ymax=income, colour=balance)) 

  • 有什么(优雅的)方法可以摆脱这种困境?
  • 我应该用其他geom 代替geom_linerange吗?
  • 我的数据格式是否正确?

【问题讨论】:

  • 我不确定我是否理解图例应该是什么样子。
  • o“收入”o“支出”| “剩余” | “赤字”

标签: r plot ggplot2


【解决方案1】:

试试

ggplot(df[df$var != "balance", ]) + 
  geom_point(
    aes(x = year, y = value, fill = var), 
        size=3, pch = 21, colour = alpha("white", 0)) +
  geom_linerange(
    aes(x = year, ymin = income, ymax = spending, colour = balance), 
        data = spread(df, var, value)) +
  scale_fill_manual(values = c("green", "red"))

输出:

主要思想是我们对颜色使用两种不同类型的美学(fill 用于点,适当的pchcolour 用于线)以便我们为每种获得单独的图例。

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2019-02-17
    • 2019-03-13
    相关资源
    最近更新 更多