簡體   English   中英

用ggplot2可視化兩點之間的差異

[英]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參數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並不能解決問題,因為它會套印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")

2.方法

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)) 

3,方法

  • 有什么(優雅)的方法可以解決這個難題?
  • 我應該使用其他的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM