2017-10-19 21 views
1

這裏有一個數據幀:擴展在GGPLOT2條來顯示數據標籤不壓扁

library(tidyverse) 

example_df <- structure(list(Funnel = c("Sessions", "AddToCart", "Registrations", "ShippingDetails", "Checkout", "Transactions"), Sum = c(1437574, 385281, 148181, 56989, 35613, 29671), End = c(NA, 1437574, 385281, 148181, 56989, 35613), xpos = c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5), Diff = c(NA, 1052293, 237100, 91192, 21376, 5942), Percent = c("NA %", "73.2 %", "61.5 %", "61.5 %", "37.5 %", "16.7 %")), .Names = c("Funnel", "Sum", "End", "xpos", "Diff", "Percent"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L)) 

這裏是一個ggplot2

ggplot(example_df, aes(x = reorder(Funnel, -Sum), y = Sum)) + 
    geom_col(alpha = 0.6, fill = "#008080") + 
    stat_summary(aes(label = scales::comma(..y..)), fun.y = 'sum', 
       geom = 'text', col = 'white', vjust = 1.5) + 
    geom_segment(aes(x=xpos, y = End, xend = xpos, yend = Sum)) + 
    geom_text(aes(x=xpos,y = End-Diff/2, label=Percent), hjust = -0.2) + 
    theme(axis.title.x = element_blank(), 
     axis.title.y = element_blank()) + 
    scale_y_continuous(labels = function(l) {l = l/1000; paste0(l, "K")}) + 

這裏是什麼樣子:

enter image description here

運輸詳情:Tran的圖上的值因爲酒吧比較小,所以閱讀很困難。

我想知道是否有一個好辦法來處理這個問題。我試圖擴大範圍:

+ expand_limits(y = -100000) 

但是,只是降低y軸。

有沒有一種明智的解決方案,以不壓扁的方式顯示數據點?如果我能夠在不影響比例的情況下將綠條降低到負區域?

+0

添加stat_summary你可以添加一個'ifelse()'語句'vjust'在'stat_summary'把標籤較高或較低的回答'y <100,000' – Mako212

+0

這將有助於爲%的數據點,我在想白色的,並以某種方式在綠色背景上顯示它們 –

+0

您可以對顏色做同樣的事情:'col = ifelse(.. y .. <100000,「black」,「white」 )' – Mako212

回答

1

很髒的解決方案,但工程。用相同的顏色和alpha添加虛擬geom_bar的波紋管每個分段(即,通過添加負向條來擴展原始分段)。

條補充:

geom_bar(data = data.frame(x = example_df$Funnel, y = -2e4), 
      aes(x, y), 
      stat = "identity", position = "dodge", 
      alpha = 0.6, fill = "#008080") 

最終代碼:

# Using OPs data 
library(ggplot2) 
ggplot(example_df, aes(x = reorder(Funnel, -Sum), y = Sum)) + 
    geom_col(alpha = 0.6, fill = "#008080") + 
    geom_segment(aes(x=xpos, y = End, xend = xpos, yend = Sum)) + 
    geom_text(aes(x=xpos,y = End-Diff/2, label=Percent), hjust = -0.2) + 
    theme(axis.title.x = element_blank(), 
     axis.title.y = element_blank()) + 
    scale_y_continuous(labels = function(l) {l = l/1000; paste0(l, "K")}) + 
    geom_bar(data = data.frame(x = example_df$Funnel, y = -2e4), 
      aes(x, y), 
      stat = "identity", position = "dodge", 
      alpha = 0.6, fill = "#008080") + 
    stat_summary(aes(label = scales::comma(..y..)), fun.y = 'sum', 
       geom = 'text', col = 'white', vjust = 1.5) + 
    theme_classic() 

簡介:

enter image description here

PS:

  • 後請將geom_bar
+1

嘿,非常感謝!看起來很棒(很快刪除此評論) –