R绘制双坐标轴

2023-11-02

目录

 

方法一:ggplot中的sec.axis函数

 

方法二:plotrix包中的twoord.plot()函数和twoord.stackplot()函数


方法一:ggplot中的sec.axis函数

ggplot2支持直接显示在辅助轴上的数据的1:1转换。 在创建辅助轴时,需重新计算第二个右侧轴上显示的参数,并将其添加到绘图中。 以下示例说明了如何利用它显示两个参数,且每个参数都有其唯一的数据范围。

library(ggplot2) # must be version > 2.2.0
library(ReadAxfBOM) 
# 数据导入
obs <- ReadAxfBOM("http://www.bom.gov.au/fwo/IDV60901/IDV60901.94866.axf")

# show first observations
head(obs)
##             Timestamp   wmo              name history_product
## 1 2016-11-15 12:30:00 94866 Melbourne Airport        IDV60901
## 2 2016-11-15 12:00:00 94866 Melbourne Airport        IDV60901
## 3 2016-11-15 11:30:00 94866 Melbourne Airport        IDV60901
## 4 2016-11-15 11:00:00 94866 Melbourne Airport        IDV60901
## 5 2016-11-15 10:30:00 94866 Melbourne Airport        IDV60901
## 6 2016-11-15 10:00:00 94866 Melbourne Airport        IDV60901
##   local_date_time local_date_time_full aifstime_utc   lat   lon apparent_t
## 1      15/12:30pm       20161115123000 2.016112e+13 -37.7 144.8        9.9
## 2      15/12:00pm       20161115120000 2.016112e+13 -37.7 144.8       10.6
## 3      15/11:30am       20161115113000 2.016112e+13 -37.7 144.8        9.9
## 4      15/11:00am       20161115110000 2.016112e+13 -37.7 144.8        9.8
## 5      15/10:30am       20161115103000 2.016111e+13 -37.7 144.8       10.1
## 6      15/10:00am       20161115100000 2.016111e+13 -37.7 144.8        9.3
##           cloud cloud_base_m cloud_oktas cloud_type_id cloud_type delta_t
## 1  Mostly clear          660           1             7    Stratus     3.4
## 2 Mostly cloudy          600           7            35       <NA>     3.5
## 3  Mostly clear          570           1             7    Stratus     3.1
## 4  Mostly clear          570           1             7    Stratus     2.9
## 5  Mostly clear          630           1             7    Stratus     3.2
## 6  Mostly clear          630           2             7    Stratus     2.5
##   gust_kmh gust_kt air_temp dewpt  press press_qnh press_msl press_tend
## 1       32      17     14.9   8.1 1020.1    1020.3    1020.1       <NA>
## 2       32      17     15.2   8.3 1020.2    1020.4    1020.2          R
## 3       28      15     14.2   8.0 1020.1    1020.3    1020.1       <NA>
## 4       30      16     14.0   8.2 1020.1    1020.3    1020.1       <NA>
## 5       26      14     14.4   8.0 1020.0    1020.2    1020.0       <NA>
## 6       26      14     13.3   8.3 1020.0    1020.2    1020.0       <NA>
##   rain_trace rel_hum sea_state swell_dir_worded swell_height swell_period
## 1          0      64        NA               NA        -9999        -9999
## 2          0      63        NA               NA        -9999        -9999
## 3          0      66        NA               NA        -9999        -9999
## 4          0      68        NA               NA        -9999        -9999
## 5          0      65        NA               NA        -9999        -9999
## 6          0      72        NA               NA        -9999        -9999
##   vis_km weather wind_dir wind_spd_kmh wind_spd_kt extreme_event
## 1     10    <NA>       SW           24          13         FALSE
## 2     30    Fine       SW           22          12         FALSE
## 3     10    <NA>       SW           20          11         FALSE
## 4     10    <NA>       SW           20          11         FALSE
## 5     10    <NA>      SSW           20          11         FALSE
## 6     10    <NA>       SW           19          10         FALSE
# 绘制气候温度图 
p <- ggplot(obs, aes(x = Timestamp))
  p <- p + geom_line(aes(y = air_temp))
p

# 增加湿度
p <- p + geom_line(aes(y = rel_hum))
p

 

由于辅助轴只能显示右y轴的一对一转换,因此我们必须转换辅助轴上显示的数据。 在这种情况下,相对湿度除以5。

p <- ggplot(obs, aes(x = Timestamp))
  p <- p + geom_line(aes(y = air_temp, colour = "Temperature"))
  
  # adding the relative humidity data, transformed to match roughly the range of the temperature
  p <- p + geom_line(aes(y = rel_hum/5, colour = "Humidity"))
  
  # now adding the secondary axis, following the example in the help file ?scale_y_continuous
  # and, very important, reverting the above transformation
  p <- p + scale_y_continuous(sec.axis = sec_axis(~.*5, name = "Relative humidity [%]"))
  
  # modifying colours and theme options
  p <- p + scale_colour_manual(values = c("blue", "red"))
  p <- p + labs(y = "Air temperature [°C]",
                x = "Date and time",
                colour = "Parameter")
  p <- p + theme(legend.position = c(0.8, 0.9))
p

scales包提供了一个重新校正的函数,scales:rescale(), 可以将辅助参数转换为任何所需范围,然后,将主要的y轴刻度线与次要的刻度线进行匹配是一个手动过程。

在这个例子中,可以说相对湿度和空气温度通过众所周知的水蒸气压和饱和蒸气压函数相互关联。 因此,在这种情况下,即使在所有温度下都不是1:1的线性关系,也可以以相同的比例将它们显示在变换的比例尺上。

rescale函数应用

lct <- Sys.getlocale("LC_TIME")  
#备份本地默认日期显示格式

Sys.setlocale("LC_TIME", "C")    
#指定标准日期显示格式

Sys.setlocale("LC_TIME",lct)     
#这一句是恢复默认系统日期显示格式
#(记得要在使用完下面的month函数之后再运行这一句,否则月份返回的是中文)

加载包:
library("lubridate")
library("ggplot2")
library("scales")
library("magrittr")
library("tidyr")
data1 <- data.frame(
  Month = seq(from = as.Date('2017-01-01'),to=as.Date('2017-06-01'),by='1 month') %>% month(label=TRUE),
  Value = runif(6,10,50) %>% round()
)
data2 <- data.frame(
  Month = seq(from = as.Date('2017-01-01'),to=as.Date('2017-06-01'),by='1 month') %>% month(label=TRUE),
  Categroy1 = runif(6,0.1,0.5) %>% round(2),
  Categroy2 = runif(6,0.1,0.5) %>% round(2)
) %>% gather(Category,Value,-1)


ggplot() +
  geom_col( data = data1,aes(x = Month,y = Value),fill="#6794a7") +
  geom_line(data = data2,aes(x = Month,y = rescale(Value,c(0,55)),colour=Category,group=Category),size=1.5) +#将折线图的数据源量级(0.0~0.5)放大到0~55的区间上
  geom_point(data = data2,aes(x = Month,y = rescale(Value,c(0,55)),colour=Category),shape=21,fill="white",size=4)+
  scale_y_continuous(breaks=pretty_breaks(5),sec.axis = sec_axis( ~rescale(.,c(0,0.5)),name = "Categroy",labels=sprintf("%d%%",(0:5)*10)))+ #将之前已经被标准化到0~50区间内的原始度量标签通过rescale函数再次标准化到0~0.5区间内
  scale_color_manual(label = c("Categroy1", "Categroy2"),values = c("#ee8f71","#C10534")) +
  labs(
    title="This is a Title!",
    subtitle="This is a Subtitle",
    caption="This is a Caption"
  )+
  theme_minimal(base_size=16) %+replace% 
  theme(
    plot.caption = element_text(hjust=0),
    plot.margin = unit(c(1,0.5,1,0.5), "lines")
  )

本例子中

p <- ggplot(obs, aes(x = Timestamp))
p <- p + geom_line(aes(y = air_temp, colour = "Temperature"))

# adding the relative humidity data, transformed to match roughly the range of the temperature
p <- p + geom_line(aes(y = rescale(rel_hum,c(0,30)), colour = "Humidity"))

# now adding the secondary axis, following the example in the help file ?scale_y_continuous
# and, very important, reverting the above transformation
p <- p + scale_y_continuous(sec.axis = sec_axis(~rescale(.,c(40,110), 
                                                         name = "Relative humidity [%]")))
                            

#sec.axis = sec_axis( ~rescale(.,c(0,0.5))
# modifying colours and theme options
p <- p + scale_colour_manual(values = c("blue", "red"))
p <- p + labs(y = "Air temperature [°C]",
              x = "Date and time",
              colour = "Parameter")
p <- p + theme(legend.position = c(0.8, 0.9))
p

 

方法二:plotrix包中的twoord.plot()函数和twoord.stackplot()函数

library(plotrix)
# NOT RUN {
xval1 <- seq.Date(as.Date("2017-01-02"),
                  as.Date("2017-01-10"), by="day")
xval2 <- seq.Date(as.Date("2017-01-01"),
                  as.Date("2017-01-15"), by="day")
going_up<-seq(3,7,by=0.5)+rnorm(9)
going_down<-rev(60:74)+rnorm(15)
twoord.plot(2:10,going_up,1:15,going_down,xlab="Sequence",
            ylab="Ascending values",rylab="Descending values",lcol=4,
            main="Plot with two ordinates - points and lines",
            do.first="plot_bg();grid(col=\"white\",lty=1)")
axis.Date(1,xval2)

# separate the lines
twoord.plot(2:10,going_up,1:15,going_down,xlab="Sequence",
            lylim=range(going_up)+c(-1,10),rylim=range(going_down)+c(-10,2),
            ylab="Ascending values",ylab.at=5,rylab="Descending values",
            rylab.at=65,lcol=4,main="Plot with two ordinates - separated lines",
            lytickpos=3:7,rytickpos=seq(55,75,by=5),
            do.first="plot_bg();grid(col=\"white\",lty=1)")

twoord.plot(2:10,going_up,1:15,going_down,xlab="Sequence",
            lylim=range(going_up)+c(-1,10),rylim=range(going_down)+c(-10,2),
            type=c("bar","l"),ylab="Ascending values",ylab.at=5,
            rylab="Descending values",rylab.at=65,
            main="Bars on left axis, lines on right axis",
            lytickpos=3:7,rytickpos=seq(55,75,by=5),
            lcol=3,rcol=4,do.first="plot_bg()")

time <- 0:25

A <- 1+1/2*sin(time/2)
B <- A + rnorm(length(A), sd=1/10)
B <- B + rnorm(length(A), sd=1/10)

sizeA <- floor(450*(1 + 1/4*sin(time/2+2))*(1+.1))
sizeB <- 1000-sizeA

C <- (A*sizeA + B*sizeB)/(sizeA+sizeB)

 

twoord.stackplot(lx=time, rx=time, ldata=cbind(sizeA, sizeB), 
                 rdata=cbind(A, B, C),  lcol=c("grey80", "white"), 
                 rcol=c("blue", "red","black"), ltype="bar", rtype=c("l","p","o"), 
                 border="grey80", lylab="Size", rylab="A,B,C", xlab="Time", 
                 main="a plot", incrylim=2/100)

 

#reverse the order of plotting
twoord.stackplot(lx=time, rx=time, ldata=cbind(sizeA, sizeB), 
                 rdata=cbind(A, B, C),  lcol=c("grey80", "white"), 
                 rcol=c("blue", "red","black"), ltype="bar", rtype=c("l","p","o"), 
                 border="grey80", lylab="Size", rylab="A,B,C", xlab="Time", 
                 main="a plot", incrylim=2/100, leftfront=TRUE)

 

参考资料:

https://rpubs.com/MarkusLoew/226759

https://rdrr.io/cran/plotrix/man/twoord.stackplot.html

https://www.rdocumentation.org/packages/plotrix/versions/3.7-8/topics/twoord.plot

https://zhuanlan.zhihu.com/p/31872309

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R绘制双坐标轴 的相关文章

  • 增加雷达图中长轴标签的空间

    我想创建一个雷达图ggirahExtra ggRadar 问题是我的标签很长并且被剪掉了 我想我可以通过添加在标签和绘图之间创建更多空间margin margin 0 0 2 0 cm to element text in axis tex
  • 自定义轴缩放后 ggplot2 缺少标签

    我正在尝试使用我的 x 轴应用自定义缩放ggplot2 and scales trans new 但是 当我这样做时 一些轴标签丢失了 有人可以帮我弄清楚为什么吗 Setup library tidyverse the data ds lt
  • 更改 R 中 ggplot geom_polygon 的颜色方案

    我正在使用地图库和 ggplot 的 geom polygon 创建地图 我只是想将默认的蓝色 红色 紫色配色方案更改为其他颜色 我对 ggplot 非常陌生 所以如果我没有使用正确的数据类型 请原谅 我使用的数据如下所示 gt head
  • 根据一个或多个下拉选项创建具有不同类型线型的折线图

    在下面闪亮的应用程序中 我尝试根据侧边栏中的下拉选择创建点线图 我已成功在选择一个指标时创建折线图 但无法选择 2 个指标 为了x and y我想要一个solid线 对于x1 and y1我想要一个dashed线和对于x2 and y2一条
  • 如何扩展 ggplot y 轴限制以包含最大值

    通常 在图中 Y 轴值标签会在绘制的最大值下方被截断 For example library tidyverse mtcars gt ggplot aes x mpg y hp geom point 我知道scale y continous
  • ggplot2中的两列分组

    是否可以按两列分组 于是叉积就画出来了 经过geom point and geom smooth 例如 frame lt data frame series lt rep c a b 6 sample lt rep c glass wate
  • 如何使用ggplot2中的线将箱线图的中值与多个组连接起来?

    我正在尝试使用 ggplot2 连接箱线图的中值 但线条不在正确的位置 这是我使用的代码 library datasets library ggplot2 data airquality airquality Month lt factor
  • ggplot2极坐标图轴标签位置

    This is just a extension for a old question ggplot2 polar plot arrows https stackoverflow com questions 10515703 ggplot2
  • 在for循环中重命名ggplot2图

    我有一个关于在 for 循环中创建 ggplot2 图表 根据迭代重命名它们 然后在网格中排列图表的问题 我想做类似这个虚拟示例的事情 library ggplot2 a c 1 2 3 b c 4 5 6 for i in c 1 5 x
  • ggplot 中跨组的连续线

    我有一个数据时间序列 其中观察了一些数据 模拟了一些数据 我想生成整个数据系列随时间变化的图 其中颜色表示数据源 但是 我只能弄清楚如何使 ggplot 中的 geom line 连接同一组中的点 这是一个例子来说明 Create samp
  • 如何用日语创建 ggplot2 标题?

    我正在准备日语演示文稿 并希望图像的标题和图例名称为日语 我可以让文本在 RStudio 中渲染得很好 但是当渲染图像时 日语字符仅显示为方框 x 10 10 y x x df data frame x y ggplot df aes x
  • 在ggplot2中创建部分虚线

    我正在 R 中创建一个图 并且需要创建一条线 其中某些值是投影 投影用虚线表示 这是代码 df data frame date c rep 2008 2013 by 1 value c 303 407 538 696 881 1094 gg
  • 我可以调整scale_color_brewer的下限吗?

    我已经订购了我想使用 color Brewer 的分类数据 但我很难看到非常低的值 有没有办法去掉这些较低的值或设置范围的下限 ggplot data frame x 1 6 y 10 15 w letters 1 6 aes x y co
  • 闪亮的点击/画笔不适用于非笛卡尔坐标?

    我正在开发一个闪亮的应用程序 它应该让用户在由 ggplot2 生成的世界地图上选择地理数据点 如这个例子 http shiny rstudio com gallery plot interaction selecting points h
  • 在 R 中,如何将 SpatialPolygons* 转换为地图对象

    我正在尝试利用ProportionalSymbolMap在此定义的地图JSS论文 http www jstatsoft org v15 i05 为了绘制比例符号 我首先需要一个地图类的对象 The methods http www ncea
  • 将其他数据集的点添加到ggplot2

    关于这个主题已经有很多问题 但我找不到能回答我的具体问题的问题 我有一个barplot see testplot1 and testplot3如下 绘制数据集 bardata如下 并希望从另一个数据集向其添加点 pointdata 请参阅简
  • R 中的 ddply:对于每个组,查找特定变量的出现百分比

    我有一个数据集 其中包含两列 user type 和滞后响应时间 以天为单位 user type imp date lag Consumer 20130613 1 Consumer 20130612 2 Consumer 20130611
  • ggplot2 中的中心图标题

    这个简单的代码 以及今天早上我的所有脚本 已经开始在 ggplot2 中给我一个偏离中心的标题 Ubuntu version 16 04 R studio version Version 0 99 896 R version 3 3 2 G
  • ggplot2 + 使用比例 X 的日期结构

    我真的需要帮助 因为我已经迷路了 我正在尝试创建一个折线图 显示几个团队一年来的表现 我将一年分为几个季度 2012 年 1 月 1 日 2012 年 4 月 1 日 2012 年 8 月 1 日 12 1 12 并将 csv 数据帧加载到
  • ggplot 按因子和梯度颜色

    我正在尝试绘制一个对两个变量 一个因子和一个强度 进行着色的图 我希望每个因素都是不同的颜色 并且我希望强度是白色和该颜色之间的渐变 到目前为止 我已经使用了诸如对因子进行分面等技术 将颜色设置为两个变量之间的相互作用 并将颜色设置为因子并

随机推荐

  • ChatGPT总结(持续更新)

    目录 体验渠道 weTab CSDN AI助手 其他插件 ChatGPT简介 ChatGPT主要用途 ChatGPT发展历程 GPT 4架构的特点和优势 ChatGPT的工作原理 神经网络和自然语言处理技术 Transformer模型 模型
  • c++纯虚数一个报错 cannot declare variable ‘a‘ to be of abstract ty

    官方点说是因为没有在子类中完成对基类的虚函数的定义 使得子类不能实例化 通俗点点说是因为父类中的纯虚数在子类中没有全部实例化 就是说明这个是做什么的 即使不用也要在子类中实例化一下 我今天就是因为想着不用先不写 结果一直报错
  • 大数据:Hive视图和索引

    一 视图 1 1 简介 Hive 中的视图和 RDBMS 中视图的概念一致 都是一组数据的逻辑表示 本质上就是一条 SELECT 语句的结果集 视图是纯粹的逻辑对象 没有关联的存储 Hive 3 0 0 引入的物化视图除外 当查询引用视图时
  • 三极管工作原理分析,精辟、透彻,看后你就懂

    说明 内容与之前那篇一样 由于之前那篇是转载百度的 现在图片受限 无法阅读 这篇自己添加了图片资源 随着科学技的发展 电子技术的应用几乎渗透到了人们生产生活的方方面面 晶体三极管作为电子技术中一个最为基本的常用器件 其原理对于学习电子技术的
  • 软件测试的原则和测试需求分析

    软件测试的原则 1 所有的测试都是以需求规格说明书为准的 2 软件测试必须基于 质量第一 的思想开展工作 如果时间与质量冲突 时间服从质量 3 事先定义好产品的质量标准 只要有了质量标准 才能根据测试结果 对产品质量进行分析和评估 4 软件
  • 蓝桥杯 基础练习 矩阵乘法

    问题描述 给定一个N阶矩阵A 输出A的M次幂 M是非负整数 例如 A 1 2 3 4 A的2次幂 7 10 15 22 输入格式 第一行是一个正整数N M 1 lt N lt 30 0 lt M lt 5 表示矩阵A的阶数和要求的幂数 接下
  • 国产代码审计工具Pinpoint介绍

    硬核国产代码审计工具Pinpoint介绍 简介 Pinpoint是由国内源伞科技所研制的一款静态代码审计工具 源伞科技公司是香港科技大学安全实验室的众多博士创建的 产品集成了实验室多年的研究成果 在众多国际顶级学术会议上都发表了成果论文 在
  • MinGW/GCC/CodeBlocks 等在 Win7 编译出现 Permission Denied 错误 - 解决方法

    本文分享了以 MinGW 为主要编译模块的编译器 如 MinGW 自身 以及Dev Cpp CodeBlocks 这些调用 MinGW 进行编译的编译器 在编译连接过程中出现 Permission Denied 错误的解决方法 同样 可能也
  • js搜索关键字,并高亮显示

    当我们搜索时 总想要自己输入的字体显示为重点 今天我为大家解决这个问题
  • 集成spring-boot-admin(一)搭建admin-server

    1 什么是SBA SBA全称为Spring Boot Admin 是一个管理和监控Spring Boot应用程序的开源项目 分为admin server 与 admin client 两个组件 admin server是一个单独的微服务 通
  • C++算术类型

    算术类型分为两类 整型 integral type 包含字符类型和布尔类型 和浮点型 算术类型的尺寸在不同机器有所差别 C 算术类型 类型 含义 最小尺寸 bit 字节 byte bool 布尔类型 未定义 1 char 字符型 8位 1
  • 不相交的线

    不相交的线 在两条独立的水平线上按给定的顺序写下 nums1 和 nums2 中的整数 现在 可以绘制一些连接两个数字 nums1 i 和 nums2 j 的直线 这些直线需要同时满足满足 nums1 i nums2 j 且绘制的直线不与任
  • 解决VirtualBox只能安装32位系统的问题

    安装VirtualBox虚拟机后发现只能安装32位系统 如下图 原因分析 电脑未开启cpu虚拟化技术 解决方式 需要到电脑BIOS里设置一下 方可安装 64位系统 操作方式 1 进入BIOS设置 根据电脑型号不同进入方式不一致 可网上查找进
  • 每天定时用爬虫爬取新闻发送给三爷

    需求 1 获取前十条科技要闻 2 通过邮件发送给指定收件人 3 定时发送 1 获取要闻 选的是新浪科技网https tech sina com cn 爬取前十名要闻 import requests from requests import
  • tensorlfow-yolov3训练

    本帖纯粹记录个人开发过程 服务器环境 V100服务器 ubuntu16 04 cuda10 0 tensorflow1 13 1 python3 5 tensorflow yolov3版本 https github com YunYang1
  • ThreadLocal理解及其内存泄露

    ThreadLocal理解及其内存泄露 ThreadLocal可以理解为 为一个线程隔离的变量 他不是一个集合 他只是一个类 这个类可以set get remove set时使用的是哪个线程 get时 也必需用哪个线程去获取 才能获取到值
  • 关于Proximal Methods,近端梯度下降的理解

    本文介绍了两种Proximal Methods的证明方法以及实现 内容主要来源于王然老师的 Proximal Methods 一文以及网络 加入了部分个人理解 由于水平有限 如有不妥之处 敬请指正 为什么会有Proximal methods
  • C语言之结构体(Struct)

    Struct 结构体的两种定义方法 方法1 方法2 结构体的成员的初始化与访问 应用举例 结构体的两种定义方法 方法1 定义一个结构体 struct Name int temp1 float temp2 1 1 定义一个结构体变量 stru
  • 拿offer必须掌握的最全SpringCloud面试题(含答案)

    今天公司的项目比较忙 远程开会和办公的沟通效率总是差那么一点 为了节约点时间 就不介绍SpringCloud了 我想只要是一名Java开发程序员 提到微服务 一定对SpringCloud的大名如雷贯耳 我们直接来看它的高频面试题吧 1 什么
  • R绘制双坐标轴

    目录 方法一 ggplot中的sec axis函数 方法二 plotrix包中的twoord plot 函数和twoord stackplot 函数 方法一 ggplot中的sec axis函数 ggplot2支持直接显示在辅助轴上的数据的