我想在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
Run Code Online (Sandbox Code Playgroud)
1.了解LONG数据
不出所料,它不适用于LONG数据,因为geom_linerange参数ymin并ymax不能正确指定.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"
Run Code Online (Sandbox Code Playgroud)
2.使用WIDE数据
我差点使用WIDE数据.情节看起来很好,但geom_point(s)缺少的传说(预期的行为).简单地添加show.legend = TRUE到两个geom_point并不能解决问题,因为它会覆盖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")
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)

geom而不是geom_linerange吗? 尝试
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"))
Run Code Online (Sandbox Code Playgroud)
主要思想是我们对颜色使用两种不同类型的美学(fill对于点,适当的pch和colour线条),以便我们为每个都获得单独的图例.