裏 RjpWiki

Julia ときどき R, Python によるコンピュータプログラム,コンピュータ・サイエンス,統計学

お絵描きだって ggplot より綺麗だよ

2019年12月26日 | ブログラミング

Create supply and demand economics curves with ggplot2

スライドや挿絵などでグラフを描くことがあるが,ggplot2 での指定はかなり煩わしい。

ggplot(mapping = aes(x = x, y = y)) +
  geom_path(data = supply, color = "#0073D9", size = 1) +
  geom_path(data = demand1, color = "#FF4036", size = 1, linetype = "dashed") +
  geom_path(data = demand2, color = "#FF4036", size = 1) +
  geom_segment(data = intersections,
    aes(x = x, y = 0, xend = x, yend = y), lty = "dotted") +
  geom_segment(data = intersections,
    aes(x = 0, y = y, xend = x, yend = y), lty = "dotted") +
  geom_text(data = plot_labels,
    aes(x = x, y = y, label = label), parse = TRUE) +
  annotate("segment", x = 3.5, xend = 4.5, y = 6, yend = 7,
    arrow = arrow(length = unit(1, "lines")), colour = "grey50") +
  geom_point(data = intersections, size = 3) +
  scale_x_continuous(expand = c(0, 0), breaks = intersections$x,
    labels = expression(Q[1], Q[2])) +
  scale_y_continuous(expand = c(0, 0), breaks = intersections$y,
    labels = expression(P[1], P[2])) +
  labs(x = "Quantity", y = "Price",
    title = "Rightward shift in demand",
    subtitle = "As demand increases, so does price") +
  coord_equal() +
  theme_classic() +
  theme(plot.title = element_text(size = rel(1.3)))

graphics::plot だと以下のように半分くらいの文字数で書ける(描ける)

old = par(mar = c(3, 3, 2.2, 0.2), mgp = c(1.6, 0.6, 0), las = 1, tck = -0.02, bty = "l")
plot(supply, col = "#0073D9", type = "l", xaxt = "n", yaxt = "n",
     xlab = "Quantity", ylab = "Price", asp = 1)

lines(demand1, col = "#FF4036", lty = "dashed")
lines(demand2, col = "#FF4036")
lines(c(0, rep(intersections[1,1], 2)), c(rep(intersections[1,2], 2), 0), lty = "dotted")
lines(c(0, rep(intersections[2,1], 2)), c(rep(intersections[2,2], 2), 0), lty = "dotted")
points(intersections, pch = 19)
text(c(8, 2, 5), 8, expression(S, D[1], D[2]), xpd = TRUE)
arrows(3.5, 6, 4.5, 7, length = 0.05, col = "grey50")
axis(1, at = intersections$x, labels = expression(Q[1], Q[2]))
axis(2, at = intersections$y, labels = expression(P[1], P[2]))
title("Rightward shift in demand", line = 1.2)
mtext ("As demand increases, so does price", line = 0.05)
par(old)



コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

PVアクセスランキング にほんブログ村

PVアクセスランキング にほんブログ村