簡體   English   中英

Alluvial plot 三變量

[英]Alluvial plot for three variabes

來自這樣的 dataframe:

data.frame(status = c("open", "close", "close", "open/close","close"), 
           stock = c("google", "amazon", "amazon", "yahoo", "amazon"), 
           newspaper = c("times", "newyork", "london", "times", "times"))

我需要如何轉換數據才能擁有沖積層 plot 像這樣

其中兩列是股票和報紙,鏈接是狀態列的頻率

有了所提供的數據,很難確切地知道必須繪制什么。 我建議這種方法的靈感來自 R 庫ggalluvial關於沖積地塊的博客

library(ggalluvial)
library(ggplot2)
library(dplyr)

df <- data.frame(status = c("open", "close", "close", "open/close", "close"), 
                 stock = c("google", "amazon", "amazon", "yahoo", "amazon"), 
                 newspaper = c("times", "newyork", "london", "times", "times"))

# Count the number of occurance for each alluvial
df <- df %>% 
  dplyr::group_by(stock, newspaper, status) %>% 
  summarise(n = n()) 

# Define the factors
df$status <- factor(df$status, levels = c("open", "open/close", "close"))
df$stock <- factor(df$stock, levels = c("google", "amazon", "yahoo"))
df$newspaper <- factor(df$newspaper, levels = c("times", "newyork", "london"))

# Plot the alluvial as in https://cran.r-project.org/web/packages/ggalluvial/vignettes/ggalluvial.html#alluvia-wide-format
ggplot2::ggplot(df, aes(y = n, axis1 = stock, axis2 = newspaper)) +
  ggalluvial::geom_alluvium(aes(fill = status), width = 1/12) +
  ggalluvial::geom_stratum(width = 1/12, fill = "black", color = "grey") +
  ggplot2::geom_label(stat = "stratum", aes(label = after_stat(stratum))) +
  ggplot2::scale_x_discrete(limits = c("stock", "newspaper"), expand = c(.05, .05)) +
  ggplot2::scale_fill_brewer(type = "qual", palette = "Set1") +
  ggplot2::ggtitle("Alluvial-Test")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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