我在 R 中有一个名为数据的数据框,如下所示:年份颜色 var 值 1 2023 蓝色 A -0.062 2023 蓝色 A 0.043 2023 蓝色 G -0.274 2023 蓝色 D 0.055 2023 蓝色...
我在 R 中有一个名为数据的数据框,如下所示:
Year Color var value
1 2023 blue A -0.06
2 2023 blue A 0.04
3 2023 blue G -0.27
4 2023 blue D 0.05
5 2023 blue L 0.18
6 2023 blue B 0.28
7 2023 blue B 0.15
8 2023 blue E 0.10
我想使用 R 中的 ggplot2 包通过 dotchart 绘制该数据。
我这样做了:
ggplot(data, aes(x = value, y = Year, color = Color)) +
geom_point(size = 3) +
facet_wrap(~ var) +
theme_minimal() +
theme(legend.position = "none")
获取:
但我希望 var 列的每个级别都像这样水平分开:
我该如何使用 ggplot2 以及所有类别的垂直线到 0 来做到这一点?此外,为什么 ggplot2 报告 2021 年而没有 2021 年的数据?我也想放弃它。
数据
structure(list(Year = c(2023, 2023, 2023, 2023, 2023, 2023, 2023,
2023, 2023, 2023, 2022, 2022, 2022, 2022, 2022, 2022, 2022, 2022,
2022, 2022, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020,
2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019), Color = c("blue",
"blue", "blue", "blue", "blue", "blue", "blue", "blue", "blue",
"blue", "red", "red", "red", "red", "red", "red", "red", "red",
"red", "red", "green", "green", "green", "green", "green", "green",
"green", "green", "green", "purple", "purple", "purple", "purple",
"purple", "purple", "purple", "purple", "purple"), var = c("A",
"A", "G", "D", "L", "B", "B", "E", "E", "C", "A", "A", "G", "D",
"L", "B", "B", "E", "E", "C", "A", "A", "G", "D", "B", "B", "E",
"E", "C", "A", "A", "G", "D", "B", "B", "E", "E", "C"), value = c(-0.06,
0.04, -0.27, 0.05, 0.18, 0.28, 0.15, 0.1, 0.02, -0.19, -0.04,
0.22, -0.13, 0.05, 0.12, 0.19, 0.07, 0, -0.42, -0.05, -0.07,
0.13, -0.23, 0.23, -0.09, -0.01, -0.11, 0.07, -0.23, -0.3, 0.15,
-0.19, 0.09, -0.03, 0.03, 0, 0.11, -0.09)), class = "data.frame", row.names = c(NA,
-38L))
要告诉 ggplot 不要绘制 2021 年, Year
变量需要是“离散的”(又称因子)。然后您可以使用 facet_grid
和 geom_vline
来获得接近所需绘图的结果。
df |>
mutate(Year=factor(Year)) |>
ggplot(aes(x = value, y = Year, color = Color)) +
geom_point(size = 3) +
facet_grid(var~., scales="free") +
labs(y="Year") +
geom_vline(xintercept=0) +
theme_bw() +
theme(legend.position = "none")