簡體   English   中英

使用 ggplot 與多個方面的交互 plot

[英]Interaction plot with multiple facets using ggplot

我在 R 工作室工作,我正在制作一個圖表,允許在輸入向量和數據庫的內容之間進行比較。

數據如下所示:

Type   P1 P2   P3  
H1   2000 60 4000
H2   1500 40 3000
H3   1000 20 2000

用於比較的輸入向量將如下所示:

Type   P1 P2   P3
   C 1200 30 5000

我希望我的最終 plot 看起來像這樣:

在此處輸入圖像描述

對於每個 P 分量,最重要的是輸入向量和不同類型之間的視覺比較。 y軸的刻度應該適應每種類型的P,因為它們之間存在很大差異。

library(dplyr)
library(tidyr)
library(ggplot2)

d %>% gather(var1, val, -Type) %>%
    mutate(input = as.numeric(d2[cbind(rep(1, max(row_number())),
                                       match(var1, names(d2)))]),
           slope = factor(sign(val - input), -1:1)) %>%
    gather(var2, val, -Type, -var1, -slope) %>%
    ggplot(aes(x = var2, y = val, group = 1)) +
    geom_point(aes(fill = var2), shape = 21) +
    geom_line(aes(colour = slope)) +
    scale_colour_manual(values = c("red", "blue")) +
    facet_grid(Type ~ var1)

數據

d = structure(list(Type = c("H1", "H2", "H3"),
                   P1 = c(2000L, 1500L, 1000L),
                   P2 = c(60L, 40L, 20L),
                   P3 = c(4000L, 3000L, 2000L)),
              class = "data.frame",
              row.names = c(NA, -3L))
d2 = structure(list(Type = "C", P1 = 1200L, P2 = 30L, P3 = 5000L),
               class = "data.frame",
               row.names = c(NA, -1L))

暫無
暫無

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

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