当前位置:   article > 正文

R语言绘图:绘制横向柱状图

R语言绘图:绘制横向柱状图

代码主要实现: 对数据进行排序,并且相同分组的数据会有相同的颜色。最后,绘制横向柱状图

# 加载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)
  )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

结果展示:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/430533
推荐阅读
相关标签
  

闽ICP备14008679号