堆积条形图,带百分比值的标签条[重复]

时间:2022-09-15 08:56:53

This question already has an answer here:

这个问题在这里已有答案:

I want to plot a table as a stacked bar plot and label the bars with the percentages. Here is an example:

我想将一个表格绘制为堆积条形图,并用百分比标记条形。这是一个例子:

data <- matrix(c(34, 66, 22, 78), ncol = 2)
data <- as.table(data)
colnames(data) <- c("shop1", "shop2")
rownames(data) <- c("prod1", "prod2")

library(reshape2)
data_m <- melt(data, varnames = c("Product", "Shop"), id.vars = "Product")

library(scales)
library(ggplot2)
ggplot(data_m, aes(x = Shop, y = value, fill = Product)) + 
geom_bar(position = "fill", stat = "identity") + 
scale_y_continuous(labels = percent_format()) +
labs(x = "", y = "")

堆积条形图,带百分比值的标签条[重复]

I tried to add the labels with

我试着添加标签

geom_text(data = data_m, aes(x = Shop, y = value, 
                         label = paste0((value/100) * 100,"%")), size=4)

but this results in 堆积条形图,带百分比值的标签条[重复]

但这会导致

EDIT: With JanLauGe's answer I get

编辑:有了JanLauGe的回答我得到了

堆积条形图,带百分比值的标签条[重复]

Now, the percentages are wrongly assigned.

现在,错误地分配了百分比。

Another remark: what to do if the column sums of the table were not the same, say 91 and 107 instead of 100 as assumed in my above example?

另一句话:如果表的列总和不相同怎么办,比如上面的例子假设的91和107而不是100?

1 个解决方案

#1


3  

Try this instead

试试这个

geom_text(data = data_m, 
          aes(x = Shop, 
              y = value / max(value), 
              label = paste0(value/100,"%")), 
          size = 4)

The problem: label position is relative to the plot area (0 to 1, 1 = max(value)).

问题:标签位置是相对于绘图区域的(0到1,1 =最大值(值))。

The solution: rescale value accordingly.

解决方案:相应地重新调整值。


EDIT: Duplicate of this post.

编辑:这篇文章的重复。

What you are looking for is this:

你在寻找的是:

ggplot(data = data_m, 
       aes(x = Shop, 
           y = value, 
           fill = Product,
           cumulative = TRUE)) +
  geom_col() +
  geom_text(aes(label = paste0(value/100,"%")), 
            position = position_stack(vjust = 0.5)) + 
  theme_minimal()

#1


3  

Try this instead

试试这个

geom_text(data = data_m, 
          aes(x = Shop, 
              y = value / max(value), 
              label = paste0(value/100,"%")), 
          size = 4)

The problem: label position is relative to the plot area (0 to 1, 1 = max(value)).

问题:标签位置是相对于绘图区域的(0到1,1 =最大值(值))。

The solution: rescale value accordingly.

解决方案:相应地重新调整值。


EDIT: Duplicate of this post.

编辑:这篇文章的重复。

What you are looking for is this:

你在寻找的是:

ggplot(data = data_m, 
       aes(x = Shop, 
           y = value, 
           fill = Product,
           cumulative = TRUE)) +
  geom_col() +
  geom_text(aes(label = paste0(value/100,"%")), 
            position = position_stack(vjust = 0.5)) + 
  theme_minimal()