[英]How to make single stacked bar chart in ggplot2?
Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"), Proportion = c(40, 30, 10, 15, 5))
Ancestry %>%
ggplot(aes(y = Proportion, fill = Race)) +
geom_bar(stat="identity", colour="white")
運行上面的代碼給我以下錯誤:
Warning in min(x, na.rm = na.rm) :
no non-missing arguments to min; returning Inf
Warning in max(x, na.rm = na.rm) :
no non-missing arguments to max; returning -Inf
Warning in min(diff(sort(x))) :
no non-missing arguments to min; returning Inf
Warning in x - width/2 :
longer object length is not a multiple of shorter object length
Warning in x + width/2 :
longer object length is not a multiple of shorter object length
Error in data.frame(list(y = c(40, 30, 10, 15, 5), fill = c(3L, 1L, 2L, :
arguments imply differing number of rows: 5, 2947
我正在尋找創建類似於此的堆疊條形圖:
您需要為x軸創建一個虛擬變量。 然后使用geom_col
其類似於geom_bar(stat = "identity")
繪制在層疊barplot + geom_text
把欄上的文本。
該圖顯示,您使用theme_economist
從ggthemes
包。
library(tidyverse)
Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"),
Proportion = c(40, 30, 10, 15, 5))
Ancestry <- Ancestry %>%
mutate(Year = "2006")
ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
geom_col() +
geom_text(aes(label = paste0(Proportion, "%")),
position = position_stack(vjust = 0.5)) +
scale_fill_brewer(palette = "Set2") +
theme_minimal(base_size = 16) +
ylab("Percentage") +
xlab(NULL)
library(ggthemes)
ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) +
geom_col() +
geom_text(aes(label = paste0(Proportion, "%")),
position = position_stack(vjust = 0.5)) +
theme_economist(base_size = 14) +
scale_fill_economist() +
theme(legend.position = "right",
legend.title = element_blank()) +
theme(axis.title.y = element_text(margin = margin(r = 20))) +
ylab("Percentage") +
xlab(NULL)
由reprex軟件包 (v0.2.0.9000)創建於2018-08-26。
我們可以創建一個虛擬變量以將所有geom_bar
分組為一組,然后使用geom_bar
創建堆積的條形圖,並使用geom_text
命名Proportions
。
library(ggplot2)
#Dummy group variable
Ancestry$row <- 1
#Create a label variable
Ancestry$percent <- (Ancestry$Proportion/sum(Ancestry$Proportion)) * 100
ggplot(Ancestry, aes(x = row,y = Proportion, fill = Race)) +
geom_bar(stat="identity") +
geom_text(aes(label = percent),
position = position_stack(vjust = 0.5))
您無需為 x 軸創建虛擬分組變量即可創建單個堆積條。 您可以在特定軸的aes()
中添加一個空字符串。 此外, theme_blank()
刪除所有不必要的網格以保持整潔。
library(tidyverse)
Ancestry <- tibble(Race = c("European", "African American", "Asian", "Hispanic", "Other"),
Proportion = c(40, 30, 10, 15, 5))
ggplot(Ancestry, aes(x = "", y = Proportion, fill = Race)) +
geom_col() +
geom_text(aes(label = paste0(Proportion, "%")),
position = position_stack(vjust = 0.5)) +
scale_fill_brewer(palette = "Set2") +
theme_blank() +
labs(x="", y="Percentage")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.