You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ggplot2绘制垂直廓线时x/y轴翻转及坐标匹配问题与对数轴需求

Fixing Your Relative Humidity Vertical Profile Plot Issues

Hey there! Let's tackle two key problems you're facing: mismatched values and coordinates, plus setting up a logarithmic pressure axis for that classic meteorological profile look. Here's a detailed breakdown and corrected code:

What Went Wrong in Your Original Script

  • You used discrete scales (scale_x_discrete/scale_y_discrete) for continuous data (pressure levels and humidity bias), which broke the value-coordinate mapping
  • After coord_flip(), the axis mappings got reversed but your scale settings didn't account for that, leading to further confusion
  • 0 hPa is an invalid pressure level for this context, and including it would cause issues with logarithmic scaling

Corrected Code (Tested with Your Data)

First, let's use the sample data you provided to verify the fix, then adapt it for batch processing:

library(ggplot2)

# Your test data
dat <- structure(list(Lev = c(1000L, 950L, 900L, 850L, 800L, 750L, 700L, 650L, 600L, 550L, 500L, 450L, 400L, 350L, 300L, 250L, 200L, 150L, 100L, 50L, 0L), 
                      April29 = c(NA, NA, NA, NA, 85, NA, NA, 39.5, 33, NA, NA, 56, NA, 57, 49, NA, NA, 42, 20, 15, NA)), 
                 class = "data.frame", row.names = c(NA,-21L))

# Build the plot with proper mappings
p <- ggplot(dat, aes(x = April29, y = Lev)) +
  # Draw line, skipping NA values to avoid breaks
  geom_line(aes(color = "April29"), na.rm = TRUE) +
  # Add red X markers for data points
  geom_point(shape = 4, size = 2, color = "red", na.rm = TRUE) +
  # Flip axes to get vertical pressure profile
  coord_flip() +
  # Clean theme matching your original style
  theme(panel.background = element_rect(fill = "white"),
        plot.margin = unit(c(1,1,1,1),"cm"),
        panel.border = element_rect(colour = "black", fill = NA, size = 1),
        axis.line.x = element_line(colour = "black"),
        axis.line.y = element_line(colour = "black"),
        axis.text = element_text(size = 15, colour = "black", family = "serif"),
        axis.title = element_text(size = 15, colour = "black", family = "serif"),
        legend.position = "") +
  # Set line color
  scale_colour_manual(name = "", values = c("April29" = "red")) +
  # Logarithmic pressure axis (y-axis after flip)
  scale_y_log10(
    breaks = c(100, 200, 300, 500, 700, 1000),  # Custom pressure ticks
    labels = c("100", "200", "300", "500", "700", "1000"),
    limits = c(100, 1000)  # Exclude 0 hPa (invalid for log scale)
  ) +
  # Continuous humidity bias axis (x-axis after flip)
  scale_x_continuous(
    limits = c(-30, 90),  # Match your original range
    breaks = seq(-30, 90, 10)  # Clear interval ticks
  ) +
  # Horizontal reference line at 0 bias (becomes vertical after flip)
  geom_vline(xintercept = 0, color = "black") +
  # Axis labels
  labs(x = "Relative Humidity Bias (%)", y = "Pressure Level (hPa)")

# Save the plot
ggsave("rh_profile_test.png", p, width = 5, height = 8)

Key Fixes Explained

  1. Clear Axis Mappings: I defined x = April29 (humidity bias) and y = Lev (pressure) first, then used coord_flip()—this makes it easier to track which scale applies to which axis after flipping.
  2. Logarithmic Pressure Axis: scale_y_log10() creates the compact lower-atmosphere spacing you want, which is standard for meteorological vertical profiles. We exclude 0 hPa because log(0) is undefined.
  3. Continuous Scales: Replaced discrete scales with continuous ones for both axes, ensuring your data values align perfectly with the plot coordinates.
  4. NA Handling: Added na.rm = TRUE to geom_line and geom_point so missing values don't break the line or create empty points.

Batch Processing Adaptation

To apply this to all your rh_profile.csv files, just swap the test data block with your file-reading loop:

library(ggplot2)

inDir <- ".."
imgDir <- ".."
inFiles <- list.files(inDir, pattern = "rh_profile.csv", full.names = TRUE)

for (inFile in inFiles) {
  dat <- read.csv(inFile, header = TRUE, sep = ",")
  
  p <- ggplot(dat, aes(x = April29, y = Lev)) +
    geom_line(aes(color = "April29"), na.rm = TRUE) +
    geom_point(shape = 4, size = 2, color = "red", na.rm = TRUE) +
    coord_flip() +
    theme(panel.background = element_rect(fill = "white"),
          plot.margin = unit(c(1,1,1,1),"cm"),
          panel.border = element_rect(colour = "black", fill = NA, size = 1),
          axis.line.x = element_line(colour = "black"),
          axis.line.y = element_line(colour = "black"),
          axis.text = element_text(size = 15, colour = "black", family = "serif"),
          axis.title = element_text(size = 15, colour = "black", family = "serif"),
          legend.position = "") +
    scale_colour_manual(name = "", values = c("April29" = "red")) +
    scale_y_log10(breaks = c(100,200,300,500,700,1000),
                  labels = c("100","200","300","500","700","1000"),
                  limits = c(100, 1000)) +
    scale_x_continuous(limits = c(-30, 90), breaks = seq(-30, 90, 10)) +
    geom_vline(xintercept = 0, color = "black") +
    labs(x = "Relative Humidity Bias (%)", y = "Pressure Level (hPa)")
  
  outImg <- paste0(imgDir, "/", gsub("\\.csv", "", basename(inFile)), ".png")
  ggsave(outImg, p, width = 5, height = 8)
}

This should give you perfectly aligned, logarithmically scaled vertical profiles as expected!

内容的提问来源于stack exchange,提问作者Lyndz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:27:47