以小平面方式堆叠计算的图

时间:2015-11-11 16:10:35

标签: r ggplot2 gridextra

我的问题类似于this question,因为我想要相同的结果。但是我不认为我的数据可以以相同的方式融化,因为它是根据TRUE / FALSE值计算的。

我的数据和图表如下:

library(ggplot2)
library(gridExtra)
library(grid)
library(scales)
library(RColorBrewer)

#test dataframe
player <- c("a", "b", "a", "b", "c", 
            "a", "a", "b", "c", "b", 
            "c", "a", "c", "c", "a",
            "c", "c", "c", "c", "c",
            "c", "c", "c", "c", "c",
            "c", "c", "c", "c", "c",
            "b", "b", "b", "b")
is.winner <- c(TRUE, TRUE, TRUE, TRUE, TRUE, 
               FALSE, TRUE, TRUE, TRUE, FALSE, 
               TRUE, TRUE, TRUE, TRUE, FALSE,
               TRUE, FALSE, FALSE, FALSE, FALSE,
               TRUE, FALSE, FALSE, FALSE, FALSE,
               FALSE, FALSE, FALSE, FALSE, FALSE,
               TRUE, TRUE, FALSE, FALSE)

df <- data.frame(player, is.winner)

df$is.winner <- factor(df$is.winner, levels=c("TRUE", "FALSE")) #swap T/F bars

# Stacked wins and losses
aa <- ggplot(data=df, aes(x=player, fill=is.winner)) +
       stat_bin(geom = "bar", position = "stack") +
       scale_fill_brewer(palette="Set2") +
       coord_flip()

# Win percentage
ab <- ggplot(data=df, aes(x=player)) +
        geom_bar(aes(fill=is.winner),position='fill')+
        scale_y_continuous(labels=percent)+
        scale_fill_brewer(palette="Set2") +
        xlab("player") +
        ylab("win%") +
        coord_flip()

grid.arrange(aa,ab,ncol=2)

enter image description here

目标是轻松查看球员胜利数和胜率,如上图所示。我认为方面风格的图表会很棒,但我不确定我处理数据的方式是否会影响我使用它的能力。感谢您的任何见解。

1 个答案:

答案 0 :(得分:1)

你可以创建一个虚拟的facetting变量,

d <- lattice::make.groups(first=df, second=df)

ggplot(data=d, aes(x=player, fill=is.winner)) +
  facet_grid(which~., scales="free") +
  geom_bar(position = "stack", data=subset(d, which=="first")) +
  geom_bar(position = 'fill', data=subset(d, which=="second")) +
  scale_fill_brewer(palette="Set2")

enter image description here

有趣的是,翻转坐标会产生不正确的情节,至少对于ggplot2的开发版本。

  last_plot() + coord_flip()

enter image description here