ggplot:以相反顺序堆叠的条形图

Mih*_*iha 2 r ggplot2

所以我有数据框

dput(df)
structure(list(Frequency = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L), .Label = c("2", "3", "4", "5"), class = "factor"), Prcentage = c(1, 
33, 58, 8, 2, 40, 53, 5), label = list("Insufficient", "Average", 
    "Good", "Excellent", "Insufficient", "Average", "Good", "Excellent"), 
    name = c("implementation", "implementation", "implementation", 
    "implementation", "energy", "energy", "energy", "energy")), .Names = c("Frequency", 
"Prcentage", "label", "name"), row.names = c(NA, 8L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)

并使用以下代码

# Get the levels for type in the required order
df$label = factor(df$label, levels = c("Unacceptable","Insufficient", "Average","Good","Excellent"))
df = arrange(df, name, desc(label))

# Format the labels and calculate their positions
df = ddply(df, .(name), transform, pos = (cumsum(Prcentage) - 0.5 * Prcentage))
df$label1 = paste0(sprintf("%.0f", df$Prcentage), "%")


# Plot
ggplot(df, aes(x = factor(name), y = Prcentage, fill = label, order=desc(label))) +
  geom_bar(stat = "identity", width = 0.5) +
  geom_text(aes(y = pos, label = label1), size = 4) +  theme_classic() + 
  scale_y_continuous(position = "top",expand = c(0, 0),breaks = seq(min(0), max(0,102), by = 10),limits = c(0,102),labels = dollar_format(suffix = "%", prefix = "")) + 
  coord_flip() +
  xlab("") + ylab("") + 
  theme(legend.position="bottom",legend.title = element_blank()) +
  scale_fill_manual(values = c("#ff0000","#fff68f","#b2b2b2","#1baf05","#006080"),drop = FALSE) 
Run Code Online (Sandbox Code Playgroud)

我制作了以下情节

在此输入图像描述

但现在我正在努力以相反的顺序获得酒吧.Sm我的输出应该以正确的值反向堆叠在条形图中(例如,1%黄色应该首先位于图的左侧,然后是33%,然后是56%,最右边的是8%).我已经尝试过这样做了

+ geom_col(position = position_stack(reverse = TRUE)) (after geom_bar)
Run Code Online (Sandbox Code Playgroud)

哪个产生了这个

在此输入图像描述

但这不正确,因为条形图中的值不正确.

我也看过这里

如何使用ggplot2上的标识控制堆积条形图的排序

ggplot2中直方图条的反向填充顺序

订购ggplot中的堆积条形图

ggplot2中直方图条的反向填充顺序

GGa*_*mba 7

标签的位置由pos值直接设置,您需要反转堆栈顺序的反转:

ggplot(df, aes(x = factor(name))) +
  geom_col(aes(y = Prcentage, fill = label), 
           position = position_stack(reverse = TRUE),
           width = .5) +
  # Set the position to its complementary
  geom_text(aes(y = 100 - pos, label = label1)) +

  # Rest of theme
  coord_flip() +
  scale_y_continuous(position = "top", 
                     expand = c(0, 0),
                     breaks = seq(min(0), max(0,102), by = 10),
                     limits = c(0,102),
                     labels = dollar_format(suffix = "%", prefix = "")) + 
  scale_fill_manual(values = c("#ff0000","#fff68f","#b2b2b2","#1baf05","#006080"), drop = FALSE) +
  xlab("") + ylab("") + 
  theme_classic() +
  theme(legend.position="bottom",legend.title = element_blank())
Run Code Online (Sandbox Code Playgroud)

  • @Miha还要注意,现在有选项可以在ggplot2中堆叠文本,而不需要创建一个`pos`变量.示例:`geom_text(aes(y = Prcentage,label = label1),position = position_stack(reverse = TRUE,vjust = .5)) (2认同)