[英]ggplot: stacked barplot in reverse order
所以我有數據框
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")
並帶有以下代碼
# 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)
我產生以下情節
但是,現在我正努力以相反的順序來獲取標准。 Sm我的輸出應該以正確的條形反向堆疊(例如,應將1%的黃色首先放置在圖的左側,然后依次放置33%,56%和最右邊的8%)。 我已經嘗試通過添加來做到這一點
+ geom_col(position = position_stack(reverse = TRUE)) (after geom_bar)
哪個產生了這個
但這是不正確的,因為條中的值不正確。
我也看過這里
標簽的位置直接由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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.