在R中绘制史密斯图表

时间:2013-09-08 22:20:24

标签: r plot complex-numbers lapply

我在R中编写了一些代码,仅使用基本图形生成史密斯圆图。 我对剧情本身很满意,但我想改进代码。 特别是我不确定4 lapply次调用,我想应该有更直接的方法在基数R中绘制一组行。

下面是我正在使用的代码,以及它生成的图表。 我是stackoverflow的新手,所以如果我应该包含更多评论或提供更多信息,请告诉我。

#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)

# given z = r + jx, calculates complex number gamma = (z-1)/(z+1)
mapping <- function(r, x) {
                z <- complex(real = r, imaginary = x); (z-1)/(z+1)}
complex_line <- function(a) {lines(Re(a), Im(a), lwd = 0.5)}

plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)

dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2)
dd <- sort(unique(dd))

smith_grid <- function (value, step) {
  # applies conformal mapping to lines having contast r
  r_grid <- lapply(seq(0, value, step), 
    FUN = function(r){mapping(r, dd[dd >= -value & dd <= value])})
  # applies conformal mapping to lines having contast x
  x_grid <- lapply(seq(-value, value, step), 
    FUN = function(x){mapping(dd[dd >= 0 & dd <= value], x)})  

  lapply(r_grid, FUN=complex_line)
  lapply(x_grid, FUN=complex_line)
}

smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)

dev.off()

enter image description here

1 个答案:

答案 0 :(得分:2)

基于Carl Witthoft评论的修订代码:

#!/usr/bin/rscript --vanilla
filename='smith_chart.pdf'
pdf(filename, 6, 6)

# applies conformal map (z-1)/(z+1) to complex number z
cmap <- function(z) (z-1)/(z+1)

plot.new()
plot.window(c(-1, 1), c(-1, 1), asp = 1)

dd <- c(seq(-100, 100, 1), seq(-10, 10, 0.1), seq(-2, 2, 0.02))
dd <- round(dd, digits = 2) # fix roundoff errors
dd <- sort(unique(dd)) # remove duplicates

smith_grid <- function (val, step) {
  # applies conformal map to lines having fixed real component
  r_grid <- outer(1i * dd[dd >= -val & dd <= val], seq(0, val, step), '+')
  r_grid <- cmap(r_grid)
  matlines(Re(r_grid), Im(r_grid), lwd = 0.5, col = 1, lty = 1)

  # applies conformal map to lines having fixed imaginary component
  x_grid <- outer(dd[dd >= 0 & dd <= val], 1i * seq(-val, val, step), '+')
  x_grid <- cmap(x_grid)
  matlines(Re(x_grid), Im(x_grid), lwd = 0.5, col = 1, lty = 1)
}

smith_grid(50, 10)
smith_grid(10, 1)
smith_grid(2, 0.2)
smith_grid(0.6, 0.1)

dev.off()