r - 具有极值的发散条形图隐藏具有小值的条形
问题描述
我正在尝试用 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 条形图(上面代码中的第二个图):
我想要的输出应该适用于右侧的极大值和左侧的小值。如果这个问题没有真正的解决方案,那么有什么替代方法可以比较如此小的和极高的值?
解决方案
一种选择是使用带有自由刻度的构面来根据 的符号分隔条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)
推荐阅读
- javascript - Angular 可以从一个 json 文件中获取数据,但不能从一个单独的文件中获取数据?
- r - R barplot - 顶部的最高值被隐藏
- windows - 我似乎有两种不同的 Vim 环境。这是什么原因造成的?
- excel - 循环遍历多个 excel 文件并从每个文件下载数据的宏
- javascript - 如何将对象数组推入数组
- c# - SqlBulkCopy 失败,KeepIdentity 设置为 true
- python - Python没有正确响应用户输入
- apache-spark - Databricks 创建一个数据框列表及其大小
- excel - 如何从excel中的登录和注销计算总工作时间和休息时间?
- javascript - angularjs指令可以编译分配第二个指令的新元素吗