棘手的数字:在 R 或 excel 中的同一 x 轴上绘制两个变量的值

Tricky Figure: Plot values of two variable on same x-axis in R or excel

我正在尝试使用此 excel Data herelike this 制作图形,但我无法将两个具有不同值的变量放在 x 轴上。

library(xlsx2)
test <- read.xlsx2("E:/Plot/oz.xlsx",1, header=TRUE) 
test$Ozone = as.numeric(as.character(test$Ozone))
test$Altitude = as.numeric(as.character(test$Altitude))
test$Pressure = as.numeric(as.character(test$Pressure))
round(test$Altitude) # i want to round the values of Altitude
library(ggplot2)
ylim.prim <- c(0, 34)   # in this example, precipitation
ylim.sec <- c(1010, 10) 
b <- diff(ylim.prim)/diff(ylim.sec)
a <- ylim.prim[1] - b*ylim.sec[1]
ggplot(test, aes(x = Ozone, y = Altitude,color = 'Ozone Partial Pressure (mPa)'))+ 
  geom_path(aes(x = Ozone))+ scale_y_continuous(name="Altitude (km)",sec.axis=sec_axis(~(.- a)/b, name = 'Pressure (hPa)'))+
  scale_x_continuous(name="Temperature (km)",sec.axis=sec_axis(~(.), name = 'Temperature (C)'))+
  theme_test() + theme(legend.position = c(0.01, 0.14),legend.justification = c(0, -4))

但我得到了这样的情节。

在此阶段,我将不胜感激。谢谢

如果每个休息时间需要两个标签,可以用 \n 将它们分开。您可以手动执行此操作,或者如果您知道使用提供给比例的 labels 参数的函数进行转换。从示例图中我瞥了一眼温度是 4x - 100 其中 x 是臭氧标签。但是,从您的数据来看,温度和臭氧似乎并不共线。

library(ggplot2)

# Downloaded from google sheets as tsv
file <- file.choose()
df <- read.table(file, sep = "\t", header = TRUE)

# Per example figure
ozone2temp <- function(x){x * 4 - 100}

# Simplified for brevity
ggplot(df) +
  geom_path(aes(Ozone, Altitude, colour = "Ozone")) +
  scale_x_continuous(
    labels = function(x) {
      paste(x, ozone2temp(x), sep = "\n")
    },
    name = "Ozone\nTemp"
  )

reprex package (v1.0.0)

于 2021 年 8 月 10 日创建

编辑:

如果你还想绘制以温度为 x 变量的海拔高度,你还需要反向转换:

library(ggplot2)

# Downloaded from google sheets as tsv
file <- file.choose()
df <- read.table(file, sep = "\t", header = TRUE)

# Per example figure
ozone2temp <- function(x){x * 4 - 100}
temp2ozone <- function(x){(x + 100) / 4}

ggplot(df, aes(y = Altitude)) +
  geom_path(aes(Ozone, colour = "Ozone")) +
  geom_path(aes(temp2ozone(Temperature), 
                colour = "Temperature")) +
  scale_x_continuous(
    labels = function(x) {
      paste(x, ozone2temp(x), sep = "\n")
    },
    name = "Ozone\nTemp"
  )

reprex package (v1.0.0)

于 2021 年 8 月 10 日创建