R语言中绘制堆叠柱状图时外边框怎么显示
要在R语言中绘制堆叠柱状图并显示外边框,可以使用ggplot2包中的geom_bar函数和theme函数。具体步骤如下:
- 安装并加载ggplot2包。
install.packages("ggplot2")
library(ggplot2)
- 创建数据框。
df <- data.frame(
group = c("A", "B", "C"),
value1 = c(10, 20, 30),
value2 = c(20, 30, 40),
value3 = c(30, 40, 50)
)
- 对数据进行堆叠,并绘制堆叠柱状图。
df_stack <- df %>%
tidyr::pivot_longer(cols = -group, names_to = "variable", values_to = "value") %>%
dplyr::group_by(group) %>%
dplyr::mutate(ymin = cumsum(value) - value,
ymax = cumsum(value))
ggplot(df_stack, aes(x = group, y = value, fill = variable)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("red", "green", "blue")) +
theme_classic() +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
- 在theme函数中增加plot.margin参数,指定上、右、下、左四个方向的边距大小,即可显示外边框
原文地址: https://www.cveoy.top/t/topic/fdmL 著作权归作者所有。请勿转载和采集!