對于了解 ggplot2 的人來說,這可能會很容易,所以也許有人可以為我做一個快速繪圖 :) 這是我想要得到的示例資料和描述。
Year <- c(1991, 1992,1995,1991,1992,1992)
Type <- c("B", "B", "D", "D", "D", "D")
df <- data.frame(Year, Type)
df
Year Type
1 1991 B
2 1992 B
3 1995 D
4 1991 D
5 1992 D
6 1992 D
我想用 ggplot2 創建一個條形圖,在 X 軸上我有不同的年份,在 Y 軸上,年份的計數就像 3 1992 年一樣,然后將 B 和 D 的條形分開。我想我必須以某種方式數數 同年在一個組中,然后將其添加到資料框中,但我不知道該怎么做。
uj5u.com熱心網友回復:
df1 <-df %>%
count(Year, Type) %>%
mutate(Freq = n/sum(n))
ggplot(df1, aes(x=Year, y=Freq, fill=Type))
geom_bar(stat="identity")
geom_text(aes(label=scales::percent(Freq)), position = position_stack(vjust = .5))
theme_classic()
labs(title = "", x = "Year", y = "%", fill="Type")
scale_fill_discrete(name= "Type")

或者你可以使用 count(Year, Type)
df1 <-df %>%
count(Year, Type)
ggplot(df1, aes(x=Year, y=n, fill=Type))
geom_bar(stat="identity")
geom_text(aes(label=n), position = position_stack(vjust = .5))
theme_classic()
labs(title = "", x = "Year", y = "Count", fill="Type")
scale_fill_discrete(name= "Type")

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377736.html
