柱状图+折线图+双Y-axis [R ggplot2]

发布于:2022-12-26 ⋅ 阅读:(666) ⋅ 点赞:(0)

前言

😑有时,在处理分层数据时,我们需要将两种或多种不同的图表类型组合成一个图,以便更好地进行可视化和分析。这些被称为“组合图”。本文中,将使用ggplot2【R】实现组合条形图和折线图。实现类似下图效果:(不要在意马赛克)

在这里插入图片描述

😑使用geom_bar() 实现柱状图,使用方法:

Syntax:geom_bar(stat, fill, color, width)
Parameters :

stat : Set the stat parameter to identify the mode.
fill : Represents color inside the bars.
color : Represents color of outlines of the bars.
width : Represents width of the bars.

😑使用geom_line() 实现折线图,使用方法:

Syntax:geom_line(mapping=NULL, data=NULL, stat=”identity”, position=”identity”,…)

准备数据

year <- c(2016, 2017, 2018, 2019, 2020, 2021,2022)
course <- c(35, 30, 40, 25, 30, 35, 65)
penroll <- c(0.3, 0.25, 0.3, 0.5, 0.4, 0.2, 0.6)

# 创建 Data Frame
```r
perf <- data.frame(year, course, penroll)
perf
###
  year   course penroll
1 2016   35     0.30
2 2017   30     0.25
3 2018   40     0.30
4 2019   25     0.50
5 2020   30     0.40
6 2021   35     0.20
7 2022   65     0.60

先试一下

library(ggplot2)

ggplot(perf) +
  geom_bar(aes(x=year, y=course),
           stat="identity", fill="black",
           colour="#006000") +
  geom_line(aes(x=year, y=penroll),
            stat="identity", color="white") +
  labs(title= "Courses vs Students Enrolled in GeeksforGeeks",
       x="Year", y="Number of Courses Sold")

😑下图,可以看到条形图的形状与预期相符,但直线图只是可见的。这是由于比例造成的,折线图表示百分比,以十进制表示,而当前Y-axis 的值非常大。因此,我们需要一个次轴(另一个Y-axis ),以便在同一图表区域中正确地展示折线。需要使用ggplot2中的scale_y_continuous() 调整Y轴区间;使用sec_axis()添加次轴(另一个Y-axis)。

在这里插入图片描述

调整

ggp <- ggplot(perf) + 
  geom_bar(aes(x=year, y=course),
           stat="identity",
           fill="black") +
  geom_line(aes(x=year, y=100*penroll),
            stat="identity",
            color="red",
            size=2) +
  labs(title= "Title",
       x="Year",
       y="Number") +
  scale_y_continuous(sec.axis=sec_axis(~.*0.01, name="Percentage", labels=scales::percent))

ggp + theme_classic()

在这里插入图片描述

Error Bar 怎么办 ?

😑这时需要Standard Deviation ( SD ),下面随便添加的,实际需要计算,使用geom_errorbar() 实现:

# 添加sd值
perf$sd <- c(2,0.8,5.3,4.2,3.1,1.7,1)

# 画图

ggp <- ggplot(perf) + 
  geom_bar(aes(x=year, y=course),
           stat="identity",
           fill="skyblue") +
  geom_errorbar(
    aes(x=year, ymin=course-sd, ymax=course+sd),
    width=0.4, 
    colour="orange", 
    alpha=0.9, 
    size=1.3) +
  geom_line(aes(x=year, y=100*penroll),
            stat="identity",
            color="black",
            size = 0.8) +
  geom_point(aes(x=year, y=100*penroll), size = 2) +
  labs(title= "Title",
       x="Year",
       y="Number") +
  scale_y_continuous(sec.axis=sec_axis(~.*0.01, name="Percentage", labels=scales::percent))

ggp + theme_classic()

在这里插入图片描述

😑其实还是差一些意思的,看起来也就那样吧……以后如果用得上,再美化吧……

欢迎关注:猪猪的乌托邦

在这里插入图片描述

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到