前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言ggplot2做双Y轴的一个简单小例子

R语言ggplot2做双Y轴的一个简单小例子

作者头像
用户7010445
发布2021-11-23 15:35:10
3.8K0
发布2021-11-23 15:35:10
举报

参考链接

  • 1、https://ggplot2.tidyverse.org/reference/sec_axis.html
  • 2、https://www.r-graph-gallery.com/line-chart-dual-Y-axis-ggplot2.html
  • 3、https://github.com/alex-koiter/Weather-and-Climate-figures
  • 4、https://twitter.com/Alex_Koiter/status/1312458166496501760/photo/1

代码主要来自于链接3

首先是准备数据的代码

代码语言:javascript
复制
library(tidyverse)
library(lubridate)
#install.packages("devtools")
#install.packages("cli")
#library(devtools)
devtools::install_github("ropensci/weathercan") 

#install.packages("weathercan")
library(weathercan)
library(patchwork)

stations_search(name = "brandon")
# Download daily weather data for 2020
df_day <- weather_dl(station_ids = 49909, 
                     interval = "day", 
                     start = "2020-01-01", 
                     end = "2020-12-31") 

# download hourly weather data
df_hour  <- weather_dl(station_ids = 49909, 
                       interval = "hour", 
                       start = "2020-09-18", 
                       end = "2020-09-28")

# Download daily climate normals
df_normal <- normals_dl(climate_ids = 5010480) %>%
  unnest(normals) %>%
  filter(period != "Year") %>%
  select(period, temp_daily_average, precip) %>%
  mutate(date = mdy(paste0(period, "-15-2020")))

# Calculate 2020 monthly precip totals
df_month <- df_day %>%
  group_by(month) %>%
  summarise(precip = sum(total_precip, na.rm = TRUE)) %>%
  mutate(date = mdy(paste0(month, "-15-2020")))

这部分代码大家可以自己试着运行一下,我用R4.0.3版本遇到的报错,没有找到解决办法,换成R4.1.0之后运行成功了

我将示例数据保存下来了,如果以上代码没有运行成功,可以在公众号获取数据,保存数据的代码

代码语言:javascript
复制
save(df_day,df_hour,df_normal,df_month,
     file = "20211121.Rdata")

现在用20211121.Rdata 作为开始

首先是读取数据集

代码语言:javascript
复制
load("20211121.Rdata")

第一个图是用到df_normal这个数据集

代码语言:javascript
复制
df_normal
dim(df_normal)

首先是一个柱形图,但这里的柱形图是通过geom_segment()函数实现的

代码语言:javascript
复制
library(ggplot2)
library(lubridate)

作图

代码语言:javascript
复制
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  gray(0.5))

对x轴操作的代码

这里涉及到时间格式的数据如何操作

代码语言:javascript
复制
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  gray(0.5))+ 
  scale_x_date(date_labels = "%b", 
               date_breaks = "1 month", 
               expand = c(0.01,0.01), 
               name = "",
               limits = (c(as_date("2020-01-01"),
                           as_date("2020-12-31")))) 

接下来就是对Y轴操作,添加双坐标轴的代码

代码语言:javascript
复制
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  gray(0.5))+ 
  scale_x_date(date_labels = "%b", 
               date_breaks = "1 month", 
               expand = c(0.01,0.01), 
               name = "",
               limits = (c(as_date("2020-01-01"),
                           as_date("2020-12-31")))) +
  scale_y_continuous(name = expression("Temperature " ( degree*C)), 
                     sec.axis = sec_axis(~ (. + 30) * 3 , 
                                         name = "Precipitation (mm)",
                                         breaks = seq(0,182,20)),
                     limits = c(-30, 30),
                     expand = c(0, 0))

这里有一个小知识点是如果要用摄氏度那个符号,他的写法是expression("Temperature " ( degree*C))

添加拟合曲线的代码

代码语言:javascript
复制
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  gray(0.5))+ 
  scale_x_date(date_labels = "%b", 
               date_breaks = "1 month", 
               expand = c(0.01,0.01), 
               name = "",
               limits = (c(as_date("2020-01-01"),
                           as_date("2020-12-31")))) +
  scale_y_continuous(name = expression("Temperature " ( degree*C)), 
                     sec.axis = sec_axis(~ (. + 30) * 3 , 
                                         name = "Precipitation (mm)",
                                         breaks = seq(0,182,20)),
                     limits = c(-30, 30),
                     expand = c(0, 0))+
  stat_smooth(data = df_normal, 
              aes(x = date, 
                  y = temp_daily_average),
              method = "loess", 
              formula = 'y~x',
              se = FALSE, 
              size = 1, 
              colour =  gray(0.5))

最后是添加了一个文本注释

代码语言:javascript
复制
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  gray(0.5)+ 
  scale_x_date(date_labels = month.abb, 
               date_breaks = "1 month", 
               expand = c(0.01,0.01), 
               name = "",
               limits = (c(as_date("2020-01-01"),
                           as_date("2020-12-31")))) +
  scale_y_continuous(name = expression("Temperature " ( degree*C)), 
                     sec.axis = sec_axis(~ (. + 30) * 3 , 
                                         name = "Precipitation (mm)",
                                         breaks = seq(0,182,20)),
                     limits = c(-30, 30),
                     expand = c(0, 0))+
  stat_smooth(data = df_normal, 
              aes(x = date, 
                  y = temp_daily_average),
              method = "loess", 
              formula = 'y~x',
              se = FALSE, 
              size = 1, 
              colour =  gray(0.5))+
  annotate(geom="text", 
           x = as_date("2020-03-15"), 
           y = 25, 
           label = "1981-2010 Climate Normals",
           color="black")

文章开头提到的参考链接3里还有3幅图的代码,大家可以自己试着重复一下

完整作图代码

代码语言:javascript
复制
x1<-tidyquant::palette_dark()
cols<-matrix(x1)[,1]
pdf(file = "p1.pdf",
    width = 9.4,
    height = 4,
    family = "serif")
ggplot() +
  theme_bw() +
  geom_segment(data = df_normal, 
               aes(x = date, 
                   y = precip/3 - 30, 
                   xend = date, 
                   yend = -30), 
               size = 8, 
               colour =  cols)+ 
  scale_x_date(date_labels = month.abb, 
               date_breaks = "1 month", 
               expand = c(0.01,0.01), 
               name = "",
               limits = (c(as_date("2020-01-01"),
                           as_date("2020-12-31")))) +
  scale_y_continuous(name = expression("Temperature " ( degree*C)), 
                     sec.axis = sec_axis(~ (. + 30) * 3 , 
                                         name = "Precipitation (mm)",
                                         breaks = seq(0,182,20)),
                     limits = c(-30, 30),
                     expand = c(0, 0))+
  stat_smooth(data = df_normal, 
              aes(x = date, 
                  y = temp_daily_average),
              method = "loess", 
              formula = 'y~x',
              se = FALSE, 
              size = 1, 
              colour =  gray(0.5))+
  annotate(geom="text", 
           x = as_date("2020-03-15"), 
           y = 25, 
           label = "1981-2010 Climate Normals",
           color="black")
dev.off()
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-11-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小明的数据分析笔记本 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考链接
  • 首先是准备数据的代码
  • 首先是读取数据集
  • 第一个图是用到df_normal这个数据集
  • 对x轴操作的代码
  • 接下来就是对Y轴操作,添加双坐标轴的代码
  • 添加拟合曲线的代码
  • 最后是添加了一个文本注释
  • 完整作图代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档