【问题标题】:geom_text on only top part of stacked bar plotgeom_text 仅在堆积条形图的顶部
【发布时间】:2014-06-05 10:00:01
【问题描述】:

我只想在堆积条形图的顶部添加标签。

这是我的数据框:

#create data frame 
building <- c("Burj \nKhalifa", "Zifeng \nTower", "Bank of \nAmerica Tower", 
              "Burj Al Arab", "Emirates \nTower One", "New York \nTimes Tower",
              "Emirates \nTower Two", "Rose Rayhaan \nby Rotana", "The \nPinnacle", 
              "Minsheng \nBank Building")
occupiable<- c(585, 317, 235, 198, 241, 220, 213, 237, 265, 237)
nonoccupiable <- c(244, 133, 131, 124, 113, 99, 97, 96, 95, 94)
df.build <- data.frame(building, occupiable, nonoccupiable)

#melt data frame for stack bar plot
df.build2 <- melt(df.build, id.vars="building")

还有我的堆积条形图:

#comparision true and percived values
ggplot(df.build2, aes(x=reorder(building, -value), y=value, fill=variable)) +
  geom_bar(stat="identity") +
  xlab("") +
  ylab("") +
 #geom_text(aes(label = c("29%" "30%", "36%", "39%", "32%", "31%", "31%", "29%", "29%", "28%")), size = 3, hjust = 0.5, vjust = 3, position = "stack") +
  theme(legend.position="top") +
  ggtitle("Porównanie wartości prawdziwych i odczuwalnych") 

我想在我的绘图代码中的geom_text() 中有这样的标签(蓝色条的高度/整个条的高度)。它应该放在蓝色区域。我该怎么做?

【问题讨论】:

  • 看看this问题,得分最高的答案看起来与您想要的解决方案非常相似。
  • 好的,但我想要只有一半的标签,(仅适用于蓝条)。因此,如果我定义 percentage &lt;- nonoccupiable/(nonoccupiable+occupiable) 并添加到 ggplot 行 geom_text(aes(y=percentage, label = paste(round(percentage*100,0),"%",sep="")), size = 3, hjust = 0.5, vjust = 3) 我得到错误:Aesthetics must either be length one, or the same length as the dataProblems:percentage

标签: r ggplot2 stack bar-chart geom-text


【解决方案1】:

另一种解决方案(我也改变了x轴文字的角度):

# creating percentage variables
df.build$occ.perc <- round(df.build$occupiable / (df.build$occupiable + df.build$nonoccupiable) * 100)
df.build$nonocc.perc <- round(df.build$nonoccupiable / (df.build$occupiable + df.build$nonoccupiable) * 100)

# melt data frame for stack bar plot![enter image description here][1]
df.build2 <- cbind(
  melt(df.build, id = c("building"), measure = c(2:3)),
  melt(df.build, id = c("building"), measure = c(4:5), value.name = "perc")
)
df.build2 <- df.build2[,-c(4,5)]
df.build2$perc <- ifelse(df.build2$variable=="occupiable", df.build2$perc==NA, df.build2$perc)

# creating the plot
ggplot(df.build2, aes(x=reorder(building, -value), y=value, fill=variable)) +
  geom_bar(stat="identity") +
  xlab("") +
  ylab("") +
  geom_text(aes(label = perc), size = 3, hjust = 0.5, vjust = 2, position = "stack") +
  theme(legend.position="top", axis.text.x = element_text(angle = 45, vjust=0.5)) +
  ggtitle("Porównanie wartości prawdziwych i odczuwalnych")

结果:

【讨论】:

    【解决方案2】:

    有 2 个问题,您在标签向量的前两个元素之间缺少逗号;并且,您的标签向量太短。即使你有看起来像 10 条的东西,实际上你有 20 条(因为它们是堆叠的)。要解决此问题,请在标签前添加 10 个空白字符串:

    geom_text(
     aes(label = c(rep("",10),
     "29%", "30%", "36%", "39%", "32%", "31%", "31%", "29%", "29%", "28%")),
    size = 3, hjust = 0.5, vjust = 3, position = "stack")
    

    这给出了:

    【讨论】: