开发者

How can I create a graph like this with ggplot in r?

开发者 https://www.devze.com 2022-12-07 22:09 出处:网络
Is this even possible with ggplot? (https://i.stack.imgur.com/wCyZN.png) I tried geom_point(), but I don\'t think it can work. I also can\'t find the semi-开发者_如何转开发circle shape.One option woul

Is this even possible with ggplot? (https://i.stack.imgur.com/wCyZN.png)

I tried geom_point(), but I don't think it can work. I also can't find the semi-开发者_如何转开发circle shape.


One option would be to use ggforce::geom_arc_bar to draw the half circles for which I set sep=pi. The rest is a lot of fiddling to put the labels at the right positions.

library(ggplot2)
library(ggforce)
library(showtext)
#> Loading required package: sysfonts
#> Loading required package: showtextdb

showtext_auto()

font_add_google("Roboto Condensed", "roboto")

dat <- data.frame(
  x = 1:5,
  r = c(.143, .321, .176, .129, -.2)
)

col <- "grey75"
scale <- .75
fontsize <- 10

ggplot(dat) +
  geom_arc_bar(
    aes(
      x0 = x, y0 = 0, r0 = 0, r = -scale * sign(r) * sqrt(abs(r)),
      amount = 1
    ),
    stat = "pie", sep = pi, fill = col
  ) +
  geom_hline(yintercept = 0, color = col) +
  geom_text(
    aes(x = x, y = sign(r) * .1, label = scales::percent(r)),
    color = "white", size = .8 + fontsize / .pt, family = "roboto"
  ) +
  annotation_custom(
    grob = grid::textGrob(
      label = "Price difference %",
      x = unit(-20, "pt"),
      y = unit(.9, "npc"),
      gp = grid::gpar(col = "white", fontsize = fontsize, fontfamily = "roboto"),
      hjust = 0, vjust = 0
    )
  ) +
  annotation_custom(
    grob = grid::textGrob(
      label = c("% that U.S. is paying more", "% that U.S. is paying less"),
      x = unit(-20, "pt"),
      y = unit(.5, "npc") + unit(c(.37, -.25), "npc"),
      gp = grid::gpar(col = col, fontsize = fontsize * .8, fontfamily = "roboto"),
      hjust = 0, vjust = 1
    )
  ) +
  scale_y_continuous(expand = c(.2, 0, .2, 0)) +
  scale_x_continuous(expand = c(0.01, 0.01)) +
  coord_fixed(clip = "off") +
  theme_void() +
  theme(
    plot.background = element_rect(fill = "black"),
    plot.margin = margin(0, 11, 0, 11, "pt"),
    axis.ticks.length.y.left = unit(20, "pt")
  )

How can I create a graph like this with ggplot in r?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号