ggpol的facet_share产生太大的利润

时间:2020-03-06 14:46:44

标签: r ggplot2

使用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

产生: enter image description here

特别关注左页边距,该页边距似乎与标签文本的比例成比例。

我的实际标签大得多,使边距更加荒谬。

有人修复吗?

1 个答案:

答案 0 :(得分:3)

最简单的方法是创建更有意义,更简洁的标签... 其他选项包括

  • 使用一些更基本的ggplot方法重新创建facet_share外观。
  • 更改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 package(v0.3.0)于2020-03-06创建

相关问题