r - 来自 ggpol 的 facet_share 创建了太大的边距
问题描述
我使用facet_share
. 使用函数示例很容易重现它们,只需对示例稍作修改。
library(ggplot2)
library(ggpol)
df <- data.frame(age = sample(1:20, 1000, replace = TRUE),
gender = c("M","F"), levels = c("M", "F"))
# Get the count per age and sex
df$count <- 1
df$age = paste(df$age, "some long string that is too long") # Added long labels
df <- aggregate(count ~ gender + age, data = df, length)
# For the horizontally shared axis, if we want to mirror the axes,
# we have to multiply the first panel by -1, and use coord_flip().
df_h <- df
df_h$count = ifelse(df_h$gender == "F", df_h$count * -1, df_h$count)
p <- ggplot(df_h, aes(x = factor(age), y = count, fill = gender)) +
geom_bar(stat = "identity") +
facet_share(~gender, dir = "h", scales = "free", reverse_num = TRUE) +
coord_flip() +
labs(x = "Age", y = "Count") +
theme(legend.position = "bottom")
p
特别关注左边距,它的大小似乎与标签文本的大小成比例。
我的实际标签要大得多,使边距更加荒谬。
有人有解决办法吗?
解决方案
最简单的方法是创建更有意义和简洁的标签......其他选项包括
- 使用一些更基本的 ggplot 方法重新创建 facet_share 外观。
- change
ggpol::facet_share
的行为并绘制类似“NULL”而不是 NA 的东西。 - 或者这里是减少 ggplotGrob 对象中列宽的解决方案:
library(ggplot2)
library(ggpol)
library(gtable)
library(grid)
p <-
ggplot(df_h, aes(x = factor(age), y = count, fill = gender)) +
geom_col() +
coord_flip()+
facet_share(~ gender, dir = "h", scales = "free", reverse_num = TRUE) +
labs(x = "Age", y = "Count") +
theme(legend.position = "bottom")
gp <- ggplotGrob(p)
#gp$layout #helps you to understand the gtable object
#gtable_show_layout(gp) #helps you to understand the gtable object
gp$widths[4] <- unit(0, 'cm') # you can modify this to your liking
grid.newpage()
grid.draw(gp)
由reprex 包(v0.3.0)于 2020 年 3 月 6 日创建
推荐阅读
- python - 带有扭曲 python HTTPS 服务器的反向代理
- python - HTTP Server 在嵌套线程方案中保持线程活动
- kotlin - 模拟 file.bufferedReader() 给出 NullPointerException
- ruby-on-rails - Activerecord Model.table_exists?没有给出正确的结果
- sprite-kit - 将 SKShapeNode 作为子级添加到 SKSpriteNode
- yii2 - 无法翻译 kartik/datecontrol/DateControl
- android - 如何在android中为图标工具栏创建大阴影
- reactjs - auth0 parseHash 无法在哈希字符串上创建属性“__enableIdPInitiatedLogin”
- java - Java:如果 doOutput=false,则无法写入 URLConnection - 调用 setDoOutput(true)
- mysql - 通过第三个表自连接两个表