为了账号安全,请及时绑定邮箱和手机立即绑定

在ggplot 2中显示堆叠条形图上的数据值

在ggplot 2中显示堆叠条形图上的数据值

慕桂英546537 2019-06-14 15:24:00
在ggplot 2中显示堆叠条形图上的数据值我想在ggplot 2中的堆叠条形图上显示数据值。这是我尝试的代码Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))Category  <- c(rep(c("A", "B", "C", "D"), times = 4))Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)Data      <- data.frame(Year, Category, Frequency)library(ggplot2)p <- qplot(Year, Frequency, data = Data, geom = "bar", fill = Category,     theme_set(theme_bw()))p + geom_text(aes(label = Frequency), size = 3, hjust = 0.5, vjust = 3, position =     "stack") 我想在每个部分的中间显示这些数据值。在这方面的任何帮助都将受到高度赞赏。谢谢
查看完整描述

2 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

从…ggplot 2.2.0标签可以通过使用position = position_stack(vjust = 0.5)在……里面geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

还请注意“position_stack()position_fill()现在,堆栈值按分组的相反顺序排列,这使得默认堆栈顺序与图例匹配。“


的旧版本有效的答案。ggplot:

这里有一种方法,用来计算条形图的中点。

library(ggplot2)library(plyr)# calculate midpoints of bars (simplified using comment by @DWin)Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency))# library(dplyr) ## If using dplyr... # Data <- group_by(Data,Year) %>%#   
    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))# plot bars and add textp <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)


查看完整回答
反对 回复 2019-06-14
?
隔江千里

TA贡献1906条经验 获得超10个赞

正如Hadley所提到的,与堆叠条形图中的标签相比,有更有效的方式来传递您的消息。事实上,堆叠的图表并不是很有效,因为条形图(每个类别)不共享一个轴,所以比较是很困难的。

在这些实例中使用两个图几乎总是更好的,共享一个公共轴。在您的示例中,我假设您希望显示总体总数,然后显示每个类别在给定年份中所占的比例。

library(grid)library(gridExtra)library(plyr)# create a new column with proportionsprop <- function(x) x/sum(x)Data <- ddply(Data,"Year",
transform,Share=prop(Frequency))# create the component graphicstotals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",
stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) +
   geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")# bring them togethergrid.arrange(totals,proportion)

如果要添加频率值,表是最佳格式。


查看完整回答
反对 回复 2019-06-14
  • 2 回答
  • 0 关注
  • 2249 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信