我已經建立了一個堆積條形圖,顯示了對不同問題的回應的相對比例。現在我想在該條形圖上顯示一個特定的回應,以顯示個人回應與回應的總體比例之間的關系。
我在這里創建了一個玩具示例:
library(ggplot2)
n = 1000
n_groups = 5
overall_df = data.frame(
state = sample(letters[1:8], n, replace = TRUE),
frequency = runif(n, min = 0, max = 1),
var_id = rep(LETTERS[1:n_groups], each = 1000 / n_groups)
)
row = data.frame(
A = "a", B = "b", C = "c", D = "h", E = "b"
)
ggplot(overall_df,
aes(fill=state, y=frequency, x=var_id))
geom_bar(position="fill", stat="identity")
此處的目標是將物件中的回應row繪制為相應條形圖中的一個點,并用一條線連接這些點。
這是所需結果的(繪制不佳)示例。謝謝你的幫助。

uj5u.com熱心網友回復:
這比我想象的要棘手。我不確定是否有任何方法可以手動計算線的 x/y 坐標。
library(dplyr)
library(ggplot2)
df <- overall_df %>% group_by(state, var_id) %>%
summarize(frequency = sum(frequency))
freq <- unlist(Map(function(d, val) {
(sum(d$frequency[d$state > val]) 0.5 * d$frequency[d$state == val]) /
sum(d$frequency)
}, d = split(df, df$var_id), val = row))
line_df <- data.frame(state = unlist(row),
frequency = freq,
var_id = names(row))
ggplot(df, aes(fill=state, y=frequency, x=var_id))
geom_col(position="fill")
geom_line(data = line_df, aes(group = 1))
geom_point(data = line_df, aes(group = 1))

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/440261.html
上一篇:R-Stat_compare_means不適合ggplot?
下一篇:用日期在r中繪制時間序列圖的問題
