【问题标题】:Exclude unused factor levels in each facet in ggplot排除 ggplot 中每个方面中未使用的因子水平
【发布时间】:2016-01-21 09:33:40
【问题描述】:

考虑这个数据框:

df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)),
             names=c("a","b","c","a","d","b","c","a","f"),
             groups=c(rep("x",3),rep("y",3),rep("z",3)))

我正在用 ggplot 绘制这个:

ggplot(df, aes(reorder(names, vars), names)) +    geom_bar(stat="identity") +
theme_bw() + facet_grid(groups~., scales="free_x") + coord_flip() +     ylab(NULL) + xlab(NULL)

看起来像这样

我现在想要以下内容:

  • 每个网格项目都应该删除未使用的项目,例如在“x”网格中不应有“d”和“f”
  • x 轴应该是“vars”列的值。每个网格中的比例应相同,应删除整体 x 比例。我只希望每个网格中的条形比例保持不变
  • 每个网格中的条形应按降序排列(顶部较长的条形)

更新

使用here 的建议进行编辑我收到此错误:

ggplot(df, aes(names,vars)) + geom_bar(stat="identity") + coord_flip() + 
  theme_bw() + facet_wrap(~groups,nrow = 3,scales = "free_x")

Error in facet_render.wrap(plot$facet, panel, plot$coordinates, theme,  : 
  ggplot2 does not currently support free scales with a non-cartesian    coord or coord_flip.
In addition: Warning message:
Stacking not well defined when ymin != 0 

当我删除 coord_flip() 时它可以工作,但我仍然收到警告,结果不是我想要的。

【问题讨论】:

  • 可以查看here
  • @akrun 我添加了其他信息

标签: r ggplot2 facet r-factor


【解决方案1】:

这是一种解决方法,但它为情节提供了一个似乎符合您的基本目标的情节。 geom_bargeom_seqment 替换,因为这似乎更接近您正在绘制的内容,并且避免了 coord_flip 的复杂性。条形的顺序由每个groupvars 的排名决定。无法直接指定 y 轴标签,但您可以使用 geom_text 将正确的 names 值放置在 y 轴旁边,以便它们充当标签。另外,我将构面标签切换到左侧,这似乎改善了构面和 y 轴标签的整体外观。

set.seed(177)
df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)),
                 names=c("a","b","c","a","d","b","c","a","f"),
                 groups=c(rep("x",3),rep("y",3),rep("z",3)))

library(ggplot2)
sp1 <- ggplot(data=transform(df, ranked=ave(vars, groups, FUN=rank)),
                  aes( x=vars, y=ranked))
sp1 <- sp1 + geom_segment( aes( xend = 0,  yend = ranked), size=10)
sp1 <- sp1 + geom_text( aes( x = min(vars), y= ranked, label = names), hjust= 4)
sp1 <- sp1 + scale_y_discrete(label=NULL)
sp1 <- sp1 + theme_bw()
sp1 <- sp1  + facet_grid( groups ~ .,  scales="free", switch="y")
plot(sp1)

情节看起来像

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2012-07-09
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多