• TNT 擂台赛
  • 序言
  • 1 曲线簇
  • 2 直方图的对数坐标
  • 3 绘制地图
  • 4 柱状图的边框
  • 5 从字符串里提取年和月
  • 6 将持续天数转换成每天出现频次
  • 7 从字符串里提取数字并做后续运算
  • 8 数据框筛选重写
  • 9 将数据框分组提取某列最大值并做后续操作
  • 后记
  • Published with bookdown

TNT 擂台赛

1 曲线簇

题目1: 函数 \(xy = z\),\(z\) 取值为 1、2、3、4, \(x\) 和 \(y\) 的取值区间为 (0, 10],如何画出这4条曲线?

N 版

x <- seq(0.1, 10, by = 0.1)
plot(x, 1 / x,
  type = "l", xlab = "x", ylab = "y"
)
for (z in 2:4) lines(x, z / x, col = z)
legend("topright",
  legend = 1:4, col = 1:4,
  lty = 1, title = "z"
)

# or
for (z in 4:1) {
  curve(z / x, 0, 10, add = z < 4, col = z)
}
legend("topright",
  legend = 4:1, col = 4:1,
  lty = 1, title = "z"
)

# or
matplot(outer(
  seq(0.1, 10, by = 0.1), 1:4,
  function(x, a) a / x
),
xlab = "x", ylab = "z/x", type = "l",
col = 1:4, lty = 1
)
legend("topright",
  legend = 4:1, col = 4:1,
  lty = 1, title = "z"
)

T 版

library(ggplot2)
library(magrittr)
expand.grid(
  x = seq(0.1, 10, by = 0.1),
  z = 1:4
) %>%
  transform(y = z / x, z = factor(z)) %>%
  ggplot() +
  geom_line(aes(x, y, color = z)) +
  coord_cartesian(ylim = c(0, 10), 
                  expand = F)

# Or
out <- ggplot(data.frame(x = c(0, 10)), 
              aes(x))

for (i in 1:4) {
  out = out + 
    stat_function(
      fun = function(.x ,z) z/.x, 
      color = i, 
      args = list(z=i),
      xlim=c(i/10,10) )
}
out


  1. 贡献者为 @medo @Liechi @dapengde @Cloud2016 @yihui @albert-R 等,来自 https://d.cosx.org/d/420766。↩