{"slug":"r-openair-package-air-quality-guide","title":"The openair Package in R: A Practical Guide for Air Quality Data","excerpt":"openair turns air quality analyses that take fifty lines of general-purpose code into one line each. A tour of the functions that matter — windRose, polarPlot, timeVariation, TheilSen and calendarPlot — with what each actually tells you.","date":"2026-08-27","author":"DSTechnoverse","image":"/blog-images/aq-stats/aq-plot-selection.svg","category":"Air Quality Analysis","tags":["openair R package","openair tutorial","R air quality analysis","wind rose R","polar plot air quality","TheilSen openair","timeVariation"],"content":"Most air quality analysis is the same handful of questions asked repeatedly: where is it coming from, when does it happen, is it getting better, and how often do we breach the limit. **openair** answers each in roughly one line.\n\n![Which plot answers which air quality question](/blog-images/aq-stats/aq-plot-selection.svg)\n\n## What openair Is\n\nAn R package written specifically for air quality data analysis, developed in the UK research community and used widely in regulatory and academic work. Its value is not that it does things other tools cannot — it is that the domain conventions are already built in.\n\n```r\ninstall.packages(\"openair\")\nlibrary(openair)\nlibrary(dplyr)\n```\n\n## The Data Format It Expects\n\nopenair is opinionated about column names, and following the convention saves constant argument-passing:\n\n| Column | Meaning |\n|---|---|\n| `date` | POSIXct timestamp — must be this name |\n| `ws` | Wind speed, m/s |\n| `wd` | Wind direction, degrees from north |\n| `pm25`, `pm10`, `no2`, `so2`, `o3` | Pollutant concentrations |\n| `site` | Station identifier, for multi-site work |\n\n```r\naq <- read.csv(\"station.csv\") |>\n  mutate(date = as.POSIXct(datetime, format = \"%d-%m-%Y %H:%M\", tz = \"Asia/Kolkata\"))\n```\n\nSet the timezone explicitly. Leaving it to the system locale is how an analysis becomes irreproducible on someone else's machine.\n\n## summaryPlot — Always Run This First\n\n```r\nsummaryPlot(aq)\n```\n\nProduces, for every variable at once: a time series, a histogram, and — most usefully — a visual map of missing data.\n\nRun it before anything else. It answers \"how bad is this dataset\" in one glance, and it routinely reveals a three-month instrument outage that would otherwise have been silently averaged over.\n\n## windRose and pollutionRose — Where Is It Coming From?\n\n```r\nwindRose(aq)\npollutionRose(aq, pollutant = \"pm25\")\n```\n\n**windRose** shows the frequency of wind by speed and direction — the meteorological context.\n\n**pollutionRose** is the more useful one. It weights each direction by pollutant concentration, so a long arm points at a direction that brings high pollution. That is a source-direction indicator, not merely a wind statistic.\n\nThe distinction matters: a direction can be rare but consistently dirty. windRose shows it as a stub; pollutionRose shows it as a problem.\n\n## polarPlot — The Most Informative Single Plot\n\n```r\npolarPlot(aq, pollutant = \"pm25\")\n```\n\nConcentration as a surface over wind speed and direction. Reading it:\n\n| Pattern | Interpretation |\n|---|---|\n| Hot spot near the centre | Local ground-level source; concentration falls as wind rises |\n| Hot spot at high wind speed, one direction | Distant or elevated source, transported in |\n| Uniform ring | Regional background rather than a local source |\n| Sharp narrow arm | A specific, identifiable source in that bearing |\n\nFor source attribution this single plot is often worth more than a chapter of description. It pairs naturally with formal [source apportionment](/blog/source-apportionment-pmf-cmb).\n\n## timeVariation — Four Diagnostics at Once\n\n```r\ntimeVariation(aq, pollutant = c(\"pm25\", \"no2\"))\n```\n\nReturns diurnal, day-of-week, monthly and hour-by-weekday panels, with confidence intervals.\n\nThe confidence intervals are the part people ignore and should not. A visually striking diurnal peak with overlapping intervals is not a reliable pattern, and openair draws them so you can tell.\n\nInterpretation shortcuts:\n\n- Twin morning and evening peaks, weaker at weekends → traffic\n- Flat overnight, sharp post-dawn rise → boundary-layer mixing, not emissions\n- Elevated at night → nocturnal inversion trapping a steady source\n- No weekday/weekend difference → non-anthropogenic or continuous industrial source\n\n## calendarPlot — Exceedances at a Glance\n\n```r\ncalendarPlot(aq, pollutant = \"pm25\", year = 2025)\n```\n\nA calendar heatmap of daily values. Immediately shows whether exceedances cluster in winter, scatter randomly, or concentrate around specific events.\n\nFor Indian datasets this usually renders the winter inversion season and the post-Diwali period unmistakably, which is far more persuasive in a report than the same fact stated in prose.\n\n## TheilSen — Trends, Properly\n\n```r\nTheilSen(aq, pollutant = \"pm25\", deseason = TRUE)\n```\n\nRuns a Theil-Sen slope estimate with Mann-Kendall significance, and `deseason = TRUE` removes the seasonal cycle first.\n\nWhy not linear regression: air quality data is skewed and gappy, which violates regression's assumptions. Theil-Sen takes the median of all pairwise slopes and is robust to both.\n\nThe output gives slope in units per year with a confidence interval and significance stars. Report all three — a slope without its interval overstates certainty. See [air quality trend analysis methods](/blog/air-quality-trend-analysis-methods).\n\n## Other Functions Worth Knowing\n\n| Function | Answers |\n|---|---|\n| `timePlot` | How do several pollutants move together? |\n| `scatterPlot` | Are two variables related, with a smoother |\n| `trendLevel` | Heatmap of concentration by hour and month |\n| `percentileRose` | How do high percentiles vary by direction? |\n| `smoothTrend` | Non-linear trend, where a straight line is wrong |\n| `selectByDate` | Subset by year, month, weekday or hour |\n| `rollingMean` | 8-hour rolling means for ozone standards |\n| `corPlot` | Correlation matrix across pollutants |\n\n`rollingMean` deserves a note: ozone and carbon monoxide standards are defined on rolling averages, not clock-hour blocks. Computing them by simple resampling gives the wrong answer.\n\n## A Complete Short Analysis\n\n```r\nlibrary(openair)\nlibrary(dplyr)\n\naq <- read.csv(\"station.csv\") |>\n  mutate(date = as.POSIXct(datetime, format = \"%d-%m-%Y %H:%M\", tz = \"Asia/Kolkata\"))\n\nsummaryPlot(aq)                                     # 1. how bad is the data\npollutionRose(aq, pollutant = \"pm25\")               # 2. which direction\npolarPlot(aq, pollutant = \"pm25\")                   # 3. what kind of source\ntimeVariation(aq, pollutant = \"pm25\")               # 4. when\ncalendarPlot(aq, pollutant = \"pm25\", year = 2025)   # 5. which days breached\nTheilSen(aq, pollutant = \"pm25\", deseason = TRUE)   # 6. is it improving\n```\n\nSix lines covering source direction, source character, temporal behaviour, exceedance pattern and long-term trend. Reproducing that in general-purpose plotting code is a day's work.\n\n## Conditioning: The Argument That Multiplies Everything\n\nNearly every openair function takes a `type` argument, which splits the plot into panels by another variable. This is where the package earns its reputation.\n\n```r\npolarPlot(aq, pollutant = \"pm25\", type = \"season\")\ntimeVariation(aq, pollutant = \"pm25\", type = \"weekday\")\ncalendarPlot(aq, pollutant = \"pm25\", type = \"year\")\n```\n\nUseful conditioning variables:\n\n| `type` value | Splits by | Reveals |\n|---|---|---|\n| `\"season\"` | Meteorological season | Whether a source is seasonal |\n| `\"year\"` | Calendar year | Whether a source appeared or stopped |\n| `\"weekday\"` | Day of week | Anthropogenic versus continuous |\n| `\"daylight\"` | Day and night | Boundary-layer versus emissions effects |\n| `\"site\"` | Station | Spatial contrast |\n| `\"ws\"` | Wind speed band | Local versus transported |\n\nThe single most diagnostic use is `polarPlot(..., type = \"season\")`. A source that appears only in winter behaves differently from one present year-round, and splitting by season separates a genuine emitter from an inversion artefact — a distinction that a combined plot hides completely.\n\nYou can also condition on your own column. Adding a `period` column marked \"before\" and \"after\" an intervention, then plotting with `type = \"period\"`, produces a direct visual before-and-after on identical axes.\n\n## Limitations\n\n**It is R-only.** No Python equivalent covers the same ground.\n\n**It assumes hourly data** in most functions. Sub-hourly needs aggregation first.\n\n**Plot customisation is constrained.** The lattice-based output is harder to restyle than ggplot2. For publication figures you may extract the data and re-plot.\n\n**It will not clean your data.** Validity flags, range checks and capture rules remain your responsibility — see [Python for air quality data analysis](/blog/python-air-quality-data-analysis-pandas) and [air quality monitoring data QA/QC](/blog/air-quality-monitoring-data-qaqc).\n\n## Getting Data Out of openair\n\nPlots are useful; the numbers behind them are what goes into a report. Most openair functions return the computed data invisibly, and capturing it saves recomputing the same statistic by hand.\n\nAssigning the result of a function gives you an object whose `data` element holds the values used to draw the plot. For `TheilSen` this is the slope, the confidence interval and the p-value per pollutant — exactly the three figures a trend statement needs. For `timeVariation` it is the hourly, weekly and monthly means with their confidence limits.\n\nTwo practical uses. First, **report the numbers, not just the picture** — a trend chart with \"slope −2.4 µg/m³ per year, 95% CI −3.1 to −1.6\" in the caption is far more defensible than the chart alone. Second, **re-plot in ggplot2** when you need publication styling that openair's lattice output cannot easily produce; you keep the domain-correct calculation and gain full control of the appearance.\n\nIt also makes results testable. A script that extracts the slope and asserts it against a previously recorded value will catch the day a data refresh silently changes a headline finding.\n\n## Frequently Asked Questions\n\n**Is openair free?** Yes, open source on CRAN.\n\n**Do I need to know R well?** No. The functions take a data frame and a pollutant name. Basic data loading is enough to get value from it.\n\n**Why must the date column be called `date`?** It is the package convention. Renaming your column is simpler than passing arguments everywhere.\n\n**Can I use it without wind data?** Yes for timeVariation, calendarPlot, TheilSen and summaryPlot. The rose and polar functions require `ws` and `wd`.\n\n**How do I handle multiple monitoring sites?** Add a `site` column and use the `type = \"site\"` argument to facet most functions by station.\n\n**Does it work with CPCB data?** Yes, once parsed and renamed to the convention. See [CAAQMS data analysis](/blog/caaqms-data-analysis-india).\n\n**Is Theil-Sen better than linear regression here?** For air quality data, generally yes — it does not assume normality and tolerates gaps and outliers. See [the Theil-Sen slope estimator](/blog/theil-sen-slope-estimator-guide).\n\n---\n\n**Need air quality data analysed properly?** DSTechnoverse handles monitoring data QA/QC, statistical analysis, trend testing and compliance reporting in R and Python. We are based in **Indore, Madhya Pradesh** and work with clients across India. See our [air quality analysis](/services/air-quality-analysis) and [EIA data analysis outsourcing](/services/eia-data-analysis-outsourcing) services, or [talk to our team](/contact).","related":[{"slug":"air-quality-analysis-complete-guide","title":"Air Quality Analysis: The Complete Guide to Air Quality Data Analysis, Methods and Services"},{"slug":"air-quality-compliance-reporting-naaqs","title":"Air Quality Compliance Reporting Against NAAQS: Percentiles, Exceedances and Defensible Statistics"},{"slug":"air-quality-forecasting-machine-learning","title":"Air Quality Forecasting with Machine Learning: Models, Features and Honest Validation"},{"slug":"air-quality-gis-mapping-interpolation","title":"Air Quality GIS Mapping: Spatial Interpolation, Kriging and Exposure Surfaces"}]}