我有一個資料集,其中一列作為所有其他列的 x 值,以及不同的 y 值,這些其他列看起來像這樣(資料框稱為 freq_dist):
| 期間 | D0 | D1 | D2 | D3 | D4 |
|---|---|---|---|---|---|
| 1 | 130 | 101 | 53 | 30 | 10 |
| 2 | 23 | 36 | 13 | 9 | 0 |
我想將所有其他列的持續時間(第 1 列)設定為 x 值,并使用 ggplot2 函式顯示條形圖。我嘗試使用 geom_bar 但不是將表中已有的值作為我的 y 值回傳,而是回傳每個值的出現次數,因此 geom_col 可能不是我想要的,但我該如何設定我的第 1 列作為所有其他列的固定 x 值?我還嘗試使用簡單的 barplot() 函式,這基本上是我正在尋找的,如下所示:
xx = freq_dist[,1]
yy = freq_dist[,2]
barplot(yy~xx)
謝謝大家!
uj5u.com熱心網友回復:
library(tidyverse)
freq_dist %>%
pivot_longer(-1) %>%
ggplot(aes(as.factor(Duration), value))
geom_col()
theme_classic()
facet_wrap(~name)
labs(x = "Duration")

uj5u.com熱心網友回復:
您需要轉為長格式并使用geom_col
ggplot(pivot_longer(freq_dist, -1), aes(factor(Duration), value, fill = name))
geom_col(width = 0.5)
scale_fill_brewer(palette = "Set1")
theme_light(base_size = 16)
labs(x = "Duration", fill = NULL)
facet_wrap(~name)
theme(legend.position = c(0.84, 0.25))

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487994.html
上一篇:如何垂直對齊圖例框的元素
