首页 > 解决方案 > ggplot条形图与条形翻转方向

问题描述

我正在尝试创建一个类似于这张图片中的图表。

您可以看到它们已经翻转了蓝色条的方向,即使它们具有正 x 值。现在,我能够重现该条形图,但条形图的方向相同。是否可以在 ggplot 中使用翻转条和正 x 值创建相同类型的图形?

标签: rggplot2

解决方案


这是一个tidyverse解决方案

图书馆

library(tidyverse)

数据

    df <-
      tibble(
        y  = letters[1:15],
        p = runif(15,5,100),
        g = as.factor(rep(0:1,c(5,10)))
      )

代码

df %>% 
  #Create auxiliary variable, where for a determined group the percentage become negative
  mutate(
    p2 = if_else(g == 0, -p,p),
    y = fct_reorder(y,p2)
    ) %>% 
  ggplot(aes(p2,y, fill = g))+
  geom_col()+
  scale_x_continuous(
    breaks = seq(-100,100,10),
    #Make the labels positive
    labels = seq(-100,100,10) %>% abs()
    )

输出

在此处输入图像描述


推荐阅读