我想創建一個圖表,在其中為資料框中的每個數量值繪制一個條目(例如 geom_point)。
下面,我創建了原始資料框的簡化版本,我想我需要在結果資料框中進行繪圖,因為我相信 ggplot 需要為每個資料框單獨一行。
在示例中,我想在位置 x 繪制 3 個紅色點,y 根據原始資料幀中每個條目的順序計數計算(在示例中,紅色為 1-3,紅色為 1-4藍色)。
我認為這可能使用 Apply 和自定義函式是可能的,但我對如何進行有點迷茫。
library(tidyverse)
origInput <- data.frame(x = c(7,2), colour = c("Red", "Blue"), quantities = c(3, 4))
desiredOutput <- data.frame(x = c(7,7,7,2,2,2,2),
colour = c("Red", "Red", "Red", "Blue", "Blue", "Blue", "Blue"),
y = c(1, 2, 3, 1, 2, 3, 4))
ggplot(desiredOutput, aes(x = x, y = y, colour = colour))
geom_point()
extrapolator <- function() {}
output <- apply(df, 2, extrapolator)
ggplot(output, ...)
uj5u.com熱心網友回復:
如評論中所述,您可以使用ungroup()復制行。要獲取 y 值,首先按顏色分組,然后將y變數設定為行號。
transformed <- origInput %>%
uncount(quantities) %>%
group_by(colour) %>%
mutate(y = row_number()) %>%
ungroup()
最后的情節是:

uj5u.com熱心網友回復:
謝謝@aosmith。
這完美地作業。
輸出 <- uncount(origInput, 數量, .id = "y")
ggplot(輸出, aes(x = x, y = y, color = colour)) geom_point()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406997.html
標籤:
