| ID | 得分1 | 得分 2 | 得分 3 | 得分 4 |
|---|---|---|---|---|
| 1 | 200 | 300 | 400 | -200 |
| 2 | 250 | -310 | -470 | -200 |
| 3 | 210 | 400 | 480 | -200 |
| 4 | 220 | -10 | -400 | -200 |
| 5 | 150 | -50 | 400 | -200 |
我是 R 新手,我想制作一個顯示每個分數平均值的圖表。然而,分數在 Y 軸上排列,并且有一條垂直線代表 0。每個分數都意味著高于零的水平條從中心到右側出現。每個分數都意味著低于零的水平條從中心向左出現。謝謝您的幫助!
uj5u.com熱心網友回復:
您可以通過首先將資料集轉換為長格式,然后計算每個分數的平均值來實作您想要的結果。ggplot2在這些資料整理步驟之后,您可以使用via繪制均值geom_col并使用添加垂直零線geom_vline:
df <- data.frame(
ID = c(1L, 2L, 3L, 4L, 5L),
score1 = c(200L, 250L, 210L, 220L, 150L),
score.2 = c(300L, -310L, 400L, -10L, -50L),
score.3 = c(400L, -470L, 480L, -400L, 400L),
score.4 = c(-200L, -200L, -200L, -200L, -200L)
)
library(dplyr)
library(tidyr)
library(ggplot2)
df1 <- df |>
tidyr::pivot_longer(-ID, names_to = "score") |>
group_by(score) |>
summarise(value = mean(value))
ggplot(df1, aes(value, score))
geom_vline(xintercept = 0)
geom_col()

編輯要標記你可以使用的酒吧geom_text。棘手的部分是對齊標簽。為此,我在正均值的情況下使用ifelse右對齊(hjust = 1)標簽,在負均值的情況下使用左對齊(hjust = 0)。實際上我做了 1.1 和 -.1 在標簽和欄之間添加一些填充。軸標簽可以通過labels比例的引數設定,在你的情況下是scale_y_discrete. 就我個人而言,我更喜歡使用命名向量,它為資料中的類別分配標簽。
ggplot(df1, aes(value, score))
geom_vline(xintercept = 0)
geom_col()
geom_text(aes(label = value, hjust = ifelse(value > 0, 1.1, -.1)), color = "white")
scale_y_discrete(labels = c("score1" = "Test1", "score.2" = "Test2", "score.3" = "Test3", "score.4" = "Test4"))

uj5u.com熱心網友回復:
與 stefan 的方法類似,但功能選擇略有不同:
- 資料:
dat <- structure(list(ID = 1:5, score1 = c(200L, 250L, 210L, 220L, 150L
), score2 = c(300L, -310L, 400L, -10L, -50L), score3 = c(400L,
-470L, 480L, -400L, 400L), score4 = c(-200L, -200L, -200L, -200L,
-200L)), class = "data.frame", row.names = c(NA, -5L))
- 函式鏈
dat %>%
select(-ID) %>%
map_df(mean) %>%
pivot_longer(everything(), names_to = "score", values_to = "means") %>%
ggplot()
coord_flip()
geom_col(aes(x = score, y = means))
- 結果

如果您想將刻度線上的標簽(“score 1”、“score2”等)更改為其他標簽,可以使用scale_x_discrete. 此外,如果您想在每個欄的頂部顯示數值,您可以使用geom_textwithhjust來調整標簽位置。
例如 :
dat %>%
select(-ID) %>%
map_df(mean) %>%
pivot_longer(everything(), names_to = "score", values_to = "means") %>%
ggplot()
coord_flip()
geom_col(aes(x = score, y = means))
scale_x_discrete(labels = c("Test A", "Test B", "Test C", "Test D"))
geom_text(aes(x = score, y = means, label = means),
hjust = c(-0.5, -0.5, -0.5, 1.1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468210.html
上一篇:使用ggplot2創建子圖
下一篇:融化頻率表以使用ggplot2
