首页 > 解决方案 > 具有极值的发散条形图隐藏具有小值的条形

问题描述

我正在尝试用 ggplot 创建一个发散的条形图。在 y 轴的一侧,我想绘制具有大值的条形图,而在另一侧,我想绘制具有小值的条形图。我已经有一些代码可以创建我想要的绘图类型,但是 y 轴右侧的高值似乎挤压了绘图左侧的 y 轴,导致具有小值的条形被隐藏。请参阅下面的代码以获取示例:

library(tidyverse)

# Create example data
df <- data.frame (Name  = c("D1","D2","D3","D4","D1","D2","D3","D4"),
                  Variable = c("group_1","group_1","group_1","group_1","group_2","group_2","group_2","group_2"),
                  Value = c(10, 20, 5, 12, 21558091, 20952575, 17442644, 20340241))

# To create divergent bars, the values of one group will be assigned as negatives
df <- df %>%
  mutate(Value = ifelse(Variable == "group_2",
                        Value,
                        -1*Value))

# Create the plot (plot1)
ggplot(df, aes(x = Name, y = Value, fill = Variable)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  scale_y_continuous(breaks = c(-30, -15, 0, 5000000, 10000000, 15000000, 20000000, 25000000),
                     labels =  c(30, 15, 0, 5000000, 10000000, 15000000, 20000000, 25000000)) +
  ylim(-30, 25000000)

# Bars from group_1 cannot be seen due to the squished y-axis on the left side 

# Forcing the ylim to a small region shows that the group_1 bars are in fact present (plot2) 
ggplot(df, aes(x = Name, y = Value, fill = Variable)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  ylim(-30, 10)

由于左侧的 y 轴被压扁,上面代码中的第一个图没有显示来自 group_1 的条形图: 在此处输入图像描述

通过强制将 ylim 限制在图左侧的一小部分,您可以看到 group_1 条形图(上面代码中的第二个图): 在此处输入图像描述

我想要的输出应该适用于右侧的极大值和左侧的小值。如果这个问题没有真正的解决方案,那么有什么替代方法可以比较如此小的和极高的值?

标签: rggplot2bar-chart

解决方案


一种选择是使用带有自由刻度的构面来根据 的符号分隔条Value,然后掩盖您正在使用构面的事实。下面的例子:

library(tidyverse)

# Create example data
df <- data.frame (Name  = c("D1","D2","D3","D4","D1","D2","D3","D4"),
                  Variable = c("group_1","group_1","group_1","group_1","group_2","group_2","group_2","group_2"),
                  Value = c(10, 20, 5, 12, 21558091, 20952575, 17442644, 20340241))

# To create divergent bars, the values of one group will be assigned as negatives
df <- df %>%
  mutate(Value = ifelse(Variable == "group_2",
                        Value,
                        -1*Value))

ggplot(df, aes(Value, Name, fill = Variable)) +
  geom_col() +
  geom_blank(aes(x = Value * 1.1)) + # Fake scale expansion
  scale_x_continuous(expand = c(0, 0)) +
  facet_grid(~ sign(Value), scales = "free_x") +
  theme(panel.spacing.x = unit(0, "cm"),
        strip.text = element_blank())

reprex 包于 2021-03-24 创建(v1.0.0)


推荐阅读