代码主要实现: 对数据进行排序,并且相同分组的数据会有相同的颜色。最后,绘制横向柱状图。
# 加载ggplot2包
library(ggplot2)# 示例数据,假设有三列:Group, Variable, Value
data <- data.frame(Group = factor(c('A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C')),Variable = c('Var10', 'Var12', 'Var23', 'Var54', 'Var15', 'Var76', 'Var27', 'Var38', 'Var19'),Value = c(5, 3, 6, 2, 8, 7, 4, 1, 9)
)# 按Value排序,确保绘图时按值大小顺序排列
data <- data[order(data$Value),]# 更新Variable为按Value排序的因子,确保绘图时Y轴按Value的大小顺序排列
data$Variable <- factor(data$Variable, levels = unique(data$Variable))data$Group <- factor(data$Group,levels = c('A', 'B', 'C'),labels = c('climate', 'topography', 'Soil'))# 绘制横向柱状图
ggplot(data, aes(x = Variable, y = Value, fill = Group)) + geom_bar(stat = "identity", position = "dodge") +coord_flip() + # 使柱状图横向显示theme_minimal() + # 使用简洁的主题scale_fill_brewer(palette = "Set1") + # 根据分组使用不同颜色labs(x = "Variable", y = "Value", title = "按Value大小顺序排列的横向柱状图", fill = "Group")+theme(text = element_text(size = 14, family = "serif"),axis.ticks.length = unit(0.2, "cm"), # 设置刻度线的长度axis.ticks = element_line(size = 1), # 设置刻度线的粗细plot.title = element_text(size = 14, colour = "black", hjust = 0.5),axis.title.y = element_text(size = 14, color = "black", vjust = 1.9, hjust = 0.5, angle = 90),legend.title = element_text(color = "black", size = 14),legend.text = element_text(color = "black", size = 14),axis.text.x = element_text(size = 14, color = "black", vjust = 0.5, hjust = 0.5, angle = 0),axis.text.y = element_text(size = 14, color = "black", vjust = 0.5, hjust = 1, angle = 0),panel.border = element_rect(color = "black", size = 1, fill = NA),# panel.grid.major = element_blank(),# panel.grid.minor = element_blank(),axis.line = element_line(colour = "black", size = 2),axis.line.x = element_line(colour = "black", size = 0),axis.line.y = element_line(colour = "black", size = 0))
结果展示: