2012-06-07 56 views
31

我正在做ggplot2中的水平点图(?),这让我想到要尝试创建一个水平barplot。但是,我发现能够做到这一点的一些限制。ggplot2中的水平Barplot

这里是我的数据:

df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"), 
       Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1)) 
df 
str(df) 

起初,我用下面的代码生成一个点图:

require(ggplot2) 
ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_point(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") + 
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) + 
    opts(plot.title = theme_text(face = "bold", size=15)) + 
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) + 
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

不过,我现在正试图创建水平barplot并找到我我无法这样做。我试过coord_flip(),那也没有帮助。

ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_bar(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") + 
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) + 
    opts(plot.title = theme_text(face = "bold", size=15)) + 
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) + 
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

任何人都可以提供如何产生ggplot2水平barplot一些帮助?

回答

80
ggplot(df, aes(x=reorder(Seller, Num), y=Avg_Cost)) + 
    geom_bar(stat='identity') + 
    coord_flip() 

没有stat='identity' ggplot希望将您的数据聚合到计数。

+1

ggplot2中的每个'geom'都有一个默认的'stat'。对于'geom_bar',默认的stat是'bin',因此Justin必须将其更改为'identity'。默认为bin的其他两个geom都是'freqpoly',当然还有'histogram'。 – Pete