【问题标题】:Centering text labels on stacked bar plots在堆积条形图上居中文本标签
【发布时间】:2015-10-18 08:47:55
【问题描述】:

条形图的颜色基于“MaskID”,在此代码中,我可以将“MaskID”名称制作成文本标签,但我希望名称以它们对应的颜色为中心。

你会怎么做?

p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))
p <- p + geom_text(aes(label = ifelse(y != 0, as.character(MaskID), ''), angle=90))

(同时考虑到 y 值为 0 的条形不会显示文本标签)

     MaskID        x     y
0       ABC    Name1     0 
1       ABC    Name2     0  
2       ABC    Name3     1
3       ABC    Name4     0
..      ...      ...   ...
100     DEF    Name1     0
101     DEF    Name2     0
102     DEF    Name3     3
103     DEF    Name4     4
104     DEF    Name5     0

这是我正在构建的图表的一部分:

【问题讨论】:

标签: r plot ggplot2 format bar-chart


【解决方案1】:

这似乎可行,尽管我认为它有点复杂。它使用ggplot_build 提取描述条形位置的数据,找到它们的中点和适当的标签,然后添加文本。

## Make the graph (-the text parts)
p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))

## Get the bar data from ggplot
dd <- ggplot_build(p)[[1]][[1]]

## Get the y-values in the middle of bars
xy <- unique(dd[dd$y != 0, c("x", "y")])
dat <- with(xy, data.frame(
    x=x,
    y=unlist(sapply(split(y, x), function(z) diff(c(0, z))/2 + head(c(0, z), -1)))
))

## Get the labels
labels <- with(df[df$y!=0,], unlist(split(MaskID, x)))

## Add the text using the new xy-values and labels
p + geom_text(data=dat, aes(x, y), label=labels, angle=90)

【讨论】:

  • 谢谢!文本标签现在位于条形的中间...但不是将 MaskID 名称作为标签,而是将条形高度的 y 值数字。
  • “标签”是什么意思? MaskID中的名字由数字和字符+数字组成
  • 哦,对不起!变量“labels”是一个文本名称列表,后面跟着对应的数字。例如,Name3 下面有一个数字,Name4 下面有另一个数字,以此类推。
  • @raychul 当你写class(df$x) 时你得到factor 吗?将其转换为字符,as.character(dt$x)
猜你喜欢
  • 2017-05-08
  • 2013-12-22
  • 2016-04-26
  • 1970-01-01
  • 2020-09-14
相关资源
最近更新 更多