R可视化和ggplot2

《R数据可视化手册》学习笔记7---注释(5)误差线

2023-10-15  本文已影响0人  RSP小白之路

写在前面。

进行可视化时,仅仅展示数据是不够的,还有各种各样的其他信息可以呈现出来帮助解读数据

这篇文章说明一些可以向主题图形添加的独立的图形元素或者文本元素,以帮助更好地呈现信息。


误差线

如何向图形添加误差线

示例数据是cabbage_exp的子集:

ce <- subset(cabbage_exp, Cultivar == "c39")
> ce
  Cultivar Date Weight        sd  n         se
1      c39  d16   3.18 0.9566144 10 0.30250803
2      c39  d20   2.80 0.2788867 10 0.08819171
3      c39  d21   2.74 0.9834181 10 0.31098410

使用geom_errorbar并将变量映射到yminymax值即可。

ggplot(ce, aes(x =Date, y = Weight)) + 
  geom_bar(stat = "identity", fill = "white", colour = "black") +
  geom_errorbar(aes(ymin = Weight - se, ymax = Weight +se), width = .2)

[图片上传失败...(image-251dd-1697416626243)]

分组的条形图在绘制误差线时,添加误差线的语句也需要分组,

ggplot(cabbage_exp, aes(x =Date, y = Weight, fill = Cultivar)) + 
  geom_bar(stat = "identity",position = "dodge") +
  geom_errorbar(aes(ymin = Weight - se, ymax = Weight +se),width=0.2)

否则会出现如下错误:

[图片上传失败...(image-eb026-1697416626243)]

正确的写法应该如下:

ggplot(cabbage_exp, aes(x =Date, y = Weight, fill = Cultivar)) + 
  geom_bar(stat = "identity",position = "dodge") +
  geom_errorbar(aes(ymin = Weight - se, ymax = Weight +se),position = position_dodge(0.9),width=0.2)

如下就显示得正常了。

[图片上传失败...(image-29d374-1697416626243)]

ggplot(ce, aes(x =Date, y = Weight)) + 
  geom_line(aes(group=1)) +
  geom_point(size=4)+
  geom_errorbar(aes(ymin = Weight - se, ymax = Weight +se), width = .2)

绘图如下:

[图片上传失败...(image-bede6d-1697416626243)]

如果要给分组折线图添加误差线,和条形图一样得道理,不再赘述。


以上。

上一篇下一篇

猜你喜欢

热点阅读