最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ggplot2 - How to reproduce these plots (made using python) in R - Stack Overflow

programmeradmin2浏览0评论

I have three factors and have produced the following plot

   mtcars%>% ggplot( aes(as.factor(carb),fill=as.factor(am)))+
    geom_bar(aes( y=..count../tapply(..count.., ..fill.. ,sum)[..fill..]), 
             position="fill")+
    facet_wrap(~as.factor(vs))+
    theme(legend.position = "bottom")

I can get what I want side by side but I'd like to produce a version where both plots are in one. Plot I’m aiming for in picture below (bottom plot).

Originals were made using python but cannot find any ggplot2 code to reproduce.

I have three factors and have produced the following plot

   mtcars%>% ggplot( aes(as.factor(carb),fill=as.factor(am)))+
    geom_bar(aes( y=..count../tapply(..count.., ..fill.. ,sum)[..fill..]), 
             position="fill")+
    facet_wrap(~as.factor(vs))+
    theme(legend.position = "bottom")

I can get what I want side by side but I'd like to produce a version where both plots are in one. Plot I’m aiming for in picture below (bottom plot).

Originals were made using python but cannot find any ggplot2 code to reproduce.

Share Improve this question edited Feb 17 at 11:24 ismirsehregal 33.5k5 gold badges45 silver badges92 bronze badges asked Feb 17 at 11:13 ABC1ABC1 11 silver badge
Add a comment  | 

1 Answer 1

Reset to default 3

You can create this kind of chart easily by using the negative values for the category to be shown on the left. To make things a bit easier I would suggest to first compute the proportions manually outside of ggplot. Finally, to add the category labels you can use annotate where I use coord_cartesian(clip="off") to draw outside of the panel borders and added some more margin at the top to make room for the labels:

library(ggplot2)
library(dplyr, warn = FALSE)

mtcars |>
  count(carb, am, vs) |>
  mutate(prop = n / sum(n), .by = c(carb, vs)) |>
  mutate(prop = if_else(vs == 0, -1, 1) * prop) |>
  ggplot(aes(
    y = as.factor(carb), x = prop,
    fill = as.factor(am)
  )) +
  geom_col(color = "white") +
  scale_x_continuous(labels = ~ scales::percent(abs(.x))) +
  theme(legend.position = "bottom") +
  annotate(
    x = c(-Inf, Inf),
    y = Inf,
    label = c("vs = 0", "vs = 1"),
    geom = "label",
    hjust = c(0, 1),
    vjust = 0,
    fill = NA,
    label.size = 0,
    fontface = "bold"
  ) +
  coord_cartesian(clip = "off") +
  theme(
    plot.margin = margin(22, 5.5, 5.5, 5.5)
  )

发布评论

评论列表(0)

  1. 暂无评论