2016-06-08 79 views
2

x轴考虑简单的例子:注释文本使用GGPLOT2

library(ggplot2) 

head(mtcars) 


# create the plot 
ggplot(mtcars, aes(factor(cyl))) + geom_bar() + theme_bw() + 
     theme(strip.text.x = element_text(size = 20, face="bold"))+ 
     xlab("number of cyl") + ylab("Count") 

现在我们可以得到平均$mpgcyl有:

aggregate(mpg ~ cyl, data = mtcars, FUN=mean) 

我怎样才能把这些平均值为X以使它们出现在对应的cyl之下。一个可以绘制表格,不知怎么写,这是每缸的......平均MPG ...

+1

也许这会有所帮助:http://stackoverflow.com/questions/16680063/how-can-i-add-a-table-to-my-ggplot2-output – beetroot

+0

是否有使用特定的原因'facet_grid'代替'ggtitle()'在剧情上放置一个标题?这可能会给潜在的答案增加不必要的复杂性。 – Uwe

+0

不,让我们删除它 – user08041991

回答

1

这里有一个简单的方法通过重写因子水平的名称做到这一点:

(注意,这是安全只有aggregate以与因子等级名称相同的顺序生成表格并且没有任何差距 - 这看起来应该是这种情况,但必须进行调查以确保它的安全。将它编码为一个循环,并期待在级别名称,以确保它们能够正确匹配)

library(ggplot2) 

head(mtcars) 

adf <- aggregate(mpg ~ cyl, data = mtcars, FUN=mean) 
mtcars$fcyl <- factor(mtcars$cyl) 
levels(mtcars$fcyl) <- sprintf("%d \n %.1f",adf$cyl,adf$mpg) 

# create the plot 
ggplot(mtcars, aes(fcyl)) + geom_bar() + theme_bw() + 
    theme(strip.text.x = element_text(size = 20, face="bold"))+ 
    xlab("number of cyl") + ylab("Count") 

产生:

enter image description here

+0

谢谢。任何意见? –