ggplot 堆积柱状图:以 Year 为横坐标,TotalArea 为纵坐标,突出显示 Top20-other 和 Other
使用 ggplot2 创建堆积柱状图,突出显示 Top20-other 和 Other 类别
本示例演示了如何使用 ggplot2 包创建堆积柱状图,以 Year 为横坐标,TotalArea 为纵坐标,并突出显示 Hybrids 中的 Top20-other 和 Other 类别。
示例代码:
# 导入必要的包
library(ggplot2)
library(dplyr)
# 创建示例数据
set.seed(123)
df <- data.frame(Year = rep(2010:2019, 35),
Hybrids = rep(paste0('Hybrid', 1:35), each = 10),
TotalArea = round(runif(350, 100, 1000), 2))
df$Hybrids[1:20] <- 'Top20-Other'
df$Hybrids[21:35] <- 'Other'
# 指定颜色
colors <- c(rep('lightgray', 20), rep('gray', 15), rev(brewer.pal(8, 'Spectral')[2:7]))
# 绘制堆积柱状图
ggplot(df, aes(x = Year, y = TotalArea, fill = Hybrids)) +
geom_col(position = 'stack') +
scale_fill_manual(values = colors) +
scale_x_continuous(breaks = seq(2010, 2019, 2)) +
theme_classic() +
theme(legend.position = 'bottom')
结果:

解释:
- 代码中使用
scale_fill_manual()函数指定不同类别的填充颜色。 Top20-Other类别使用浅灰色 (lightgray) 填充,Other类别使用灰色 (gray) 填充。- 其他 33 个类别使用
brewer.pal()函数生成的渐变色系填充。 scale_x_continuous()函数设置横坐标的刻度,theme_classic()函数设置主题。theme(legend.position = 'bottom')将图例放置在底部。
注意:
- 此示例代码仅供参考,实际应用中需要根据数据进行调整。
- 可根据需要调整颜色、主题等设置。
原文地址: https://www.cveoy.top/t/topic/nGIH 著作权归作者所有。请勿转载和采集!