相关文章推荐
不开心的烤面包  ·  R语言ggplot2做双Y轴的一个简单小例子 - ·  1 月前    · 
深情的鸡蛋  ·  消费主义背景下经典广告英语的语言特点--传媒 ...·  5 月前    · 
傲视众生的桔子  ·  去广东必点的8道菜,据说是“广府菜之魂”_白 ...·  8 月前    · 
英俊的紫菜  ·  马达加斯加国家概况-国家国际发展合作署·  9 月前    · 
从容的路灯  ·  另一个波琳家的女孩- 知乎·  2 年前    · 
豪情万千的楼梯  ·  北京大学城市与环境学院_个人简历·  2 年前    · 
小百科  ›  R语言ggplot2做双Y轴的一个简单小例子 -
ggplot2 r语言 date函数 date
不开心的烤面包
1 月前
用户7010445

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

腾讯云
开发者社区
文档 建议反馈 控制台
首页
学习
活动
专区
圈层
工具
MCP广场
文章/答案/技术大牛
发布
用户7010445
社区首页 > 专栏 > R语言ggplot2做双Y轴的一个简单小例子

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

作者头像
用户7010445
发布 于 2021-11-23 15:35:10
发布 于 2021-11-23 15:35:10
5.1K 0
举报
文章被收录于专栏: 小明的数据分析笔记本 小明的数据分析笔记本

参考链接

  • 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", 
 
推荐文章
不开心的烤面包  ·  R语言ggplot2做双Y轴的一个简单小例子 -
1 月前
深情的鸡蛋  ·  消费主义背景下经典广告英语的语言特点--传媒--人民网
5 月前
傲视众生的桔子  ·  去广东必点的8道菜,据说是“广府菜之魂”_白切鸡_广州_烧鹅
8 月前
英俊的紫菜  ·  马达加斯加国家概况-国家国际发展合作署
9 月前
从容的路灯  ·  另一个波琳家的女孩- 知乎
2 年前
豪情万千的楼梯  ·  北京大学城市与环境学院_个人简历
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
小百科 - 百科知识指南
© 2024 ~ 沪ICP备11025650号