[英]Histogram with multiple bins and groups
使用一些隨機示例數據,以下代碼是一個tidyverse
解決方案,它為您提供一個條形圖或柱形圖(因為您的數據已經分箱,這是要走的路)模仿一個數據集的 excel 圖表。 As you already guessed the tricky part is getting your data into R (to this end: have a look at the readxl
package) and to rearrange it for plotting (this is done via pivot_longer
from the tidyr
package and mutate
from dplyr
both of which are tidyverse
的一部分。至於繪圖部分,我使用ggplot2
- 你可能已經猜到了(; - 也是tidyverse
的一部分。
# Example data set
set.seed(42)
df <- data.frame(
distance = paste0(seq(0, 3.5, by = 0.5), "-", seq(0.5, 4, by = 0.5)),
`2015` = round(runif(8) * 8, 0),
`2016` = round(runif(8) * 8, 0),
`2017` = round(runif(8) * 8, 0)
)
df
#> distance X2015 X2016 X2017
#> 1 0-0.5 7 5 8
#> 2 0.5-1 7 6 1
#> 3 1-1.5 2 4 4
#> 4 1.5-2 7 6 4
#> 5 2-2.5 5 7 7
#> 6 2.5-3 4 2 1
#> 7 3-3.5 6 4 8
#> 8 3.5-4 1 8 8
library(tidyverse)
df %>%
# Convert the dataset to long format
pivot_longer(-distance, names_to = "Year", values_to = "Value") %>%
# format the dates, get rid of leading Xs
mutate(Year = gsub("^X", "", Year)) %>%
ggplot(aes(distance, Value, fill = Year)) +
# Column chart. Add some width between columns
geom_col(position = position_dodge2(2)) +
scale_y_continuous(expand = expansion(mult = c(0, .05))) +
scale_fill_manual(values = c("blue", "orange", "grey")) +
# Get rid of axis and legend labels
labs(y = "", x = "", fill = "") +
theme_bw() +
theme(legend.position = "bottom")
由reprex package (v0.3.0) 於 2020 年 4 月 5 日創建
是的,您將不得不重組您的數據。 您可以在 R 中執行此操作,如 @stefan 所示,或者如果它具有挑戰性,您可以在 excel 本身中執行此操作。 整齊的數據易於 plot 和分析(整理數據見第 12.1節,可視化見第3.7、3.8 節)。 整潔的數據看起來像是由四列組成 - 距離、價值、價值_年、價值_組。
例如,我將一些數據存儲為制表符分隔文件 (testdata.txt) 並使用 tidyverse 的 read_delim function 讀取。 以下是示例代碼:
library(tidyverse)
foo <- read_delim("testdata.txt", delim = "\t")
foo %>% mutate(Val_year = factor(Val_year, levels=c("2015","2016","2017"))) %>%
ggplot() + geom_bar(aes(x=Dist, y=Val, fill = Val_year), stat = "identity", position = "dodge") + facet_grid(.~Val_grp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.