[英]Visualizing the difference between two points with ggplot2
我想用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數據,因為無法正確指定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"
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")
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
嗎? 嘗試
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
點,用適當的pch
fill
顏色,並用colour
表示線條),以便為每種colour
獲得單獨的圖例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.