使用一些随机示例数据,以下代码是一个tidyverse 解决方案,它为您提供一个条形图或柱形图(因为您的数据已经分箱,这是要走的路)模仿您的一个数据集的 Excel 图表。正如您已经猜到的那样,棘手的部分是将您的数据放入 R 中(为此:查看readxl 包)并重新排列它以进行绘图(这是通过pivot_longer 来自tidyr 包和@ 987654327@ from dplyr 两者都是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 日创建