朱zhu

V1

2023/03/13阅读:19主题:橙心

R数据可视化--带误差棒的条形图

数据可视化--带误差棒的条形图

条形图基础绘图

创建一个数据集,列出每种水果的均价及其置信区间。

各位小伙伴注意下,该数据集直接提供了种类及其相应的例数,有些数据需转化为此格式才能方便绘画。

fruits <- tribble(
  ~category, ~Meanprice, ~lower, ~upper,
  "apple"2052,
  "banana"2537,
  "oranges"5583,
  "lemon"45,137,
  "pear"33,129
)
fruits

绘图

ggplot(fruits, aes(x = category, y = Meanprice, fill = category)) + #fill以水果类型进行填充
  geom_col(width = 0.3)

添加误差棒

ggplot(fruits, aes(x = category, y = Meanprice, fill = category)) + #fill以水果类型进行填充
  geom_col(width = 0.3) +
  geom_errorbar(aes(ymin = Meanprice - lower, ymax = Meanprice + upper), width = 0.1#添加误差棒

进一步美化

library(ggthemes)
library(ggtext)
ggplot(fruits, aes(x = category, y = Meanprice, fill = category)) + #fill以水果类型进行填充
  geom_col(width = 0.3) + #设置条形图宽度
  geom_hline(aes(yintercept = 0)) + #添加x轴(即y = 0的水平线)
  geom_errorbar(aes(ymin = Meanprice - lower, ymax = Meanprice + upper), width = 0.1) + #添加误差棒
  geom_text(aes(label = Meanprice, y = Meanprice + upper + 4), size = 4) + #添加数据标签
  scale_fill_brewer(palette = "Blues") + #设置填充色
  scale_y_continuous(limits = c(070), breaks = c(seq(07010))) + #设置y轴范围及轴标签间隔
  theme_few() +
  theme(  
    axis.text.x = element_text(angle = 0), #设置x轴文本角度
    panel.background = element_rect(fill="#FFFFF3"),#设置绘图面板填充色
    plot.background = element_rect(fill="#FFFFF3",colour = "#FFFFF3"), #设置图背景颜色
    legend.position = "right",#调整图例位置
    legend.title = element_text(size = 13), #调整图例标题文本大小
    legend.text = element_text(size = 11#调整图例文本大小
  ) +
 ggtitle("Fruits")

OK!今天的教程就到这里了。

更多数据分析可视化教程请关注微信公众号

分类:

后端

标签:

后端

作者介绍

朱zhu
V1