[英]Reformatting data frame to be able to plot bar charts with ggplot2
這些問題涉及重新格式化數據框(df)以便通過ggplo2()在同一圖上顯示三個條形圖。 感謝您的每一個回應!
我在df中的數據:
colA, colB, colC
label1, label1, label2
label3, label1, label3
label4, label4, label2
label5, label4, label5
利用這些數據,我可以使用下面的命令為每列創建條形圖,該命令顯示給定列中每個標簽的計數。
pl <- ggplot(df,aes(x=colA))
pl1 <- pl + geom_bar()
pl1 <- pl1 + theme(axis.text.x = element_text(angle = 90, hjust = 1))
pl1 <- pl1 + xlab('Labels')+ ylab('Count')
pl1 <- pl1 + ggtitle('Some Title') + theme(plot.title = element_text(hjust = 0.5))
print(pl1)
但是,我想在同一條形圖上而不是在單獨的圖中描述所有三列的計數。 我不想匯總三列的計數,而是在同一張圖中分別描繪各列,也許每個標簽都成組放置,但是我不知道在這種情況下分組是否是正確的選擇。 我認為數據格式需要創建所需的圖表:
Labels, colA, colB, colC
label1, 1, 2, 0,
label2, 0, 0, 2,
label3, 1 0, 1,
label4, 1, 2, 0,
label5, 1, 0, 1,
問題1:如何將數據從當前格式重新格式化為所需格式?
問題2:數據如何與計數一起顯示在同一條形圖上?
一種方法可能是使用gather
將數據轉換為長格式,然后繪制數據
library(dplyr)
library(tidyr)
library(ggplot2)
df %>%
gather(column_name, column_value) %>%
group_by(column_value, column_name) %>%
tally() %>%
ggplot(aes(x = column_value, y = n, fill = column_name)) +
geom_bar(stat = "identity") +
xlab('Labels') +
ylab('Count')
其中傳遞給ggplot
最終數據是
# column_value column_name n
#1 label1 colA 1
#2 label1 colB 2
#3 label2 colC 2
#4 label3 colA 1
#5 label3 colC 1
#6 label4 colA 1
#7 label4 colB 2
#8 label5 colA 1
#9 label5 colC 1
樣本數據:
df <- structure(list(colA = c("label1", "label3", "label4", "label5"
), colB = c("label1", "label1", "label4", "label4"), colC = c("label2",
"label3", "label2", "label5")), .Names = c("colA", "colB", "colC"
), class = "data.frame", row.names = c(NA, -4L))
對於所需的格式,您可以輕松地進行tidyr::gather
和reshape2::dcast
組合。
library(tidyverse)
library(reshape2)
df %>%
gather(column, label) %>%
dcast(label ~ column, fun.aggregate = length, value.var = "column")
# label colA colB colC
# 1 label1 1 2 0
# 2 label2 0 0 2
# 3 label3 1 0 1
# 4 label4 1 2 0
# 5 label5 1 0 1
用R語言來說,這是較寬的格式。 使用ggplot2
,使用long
格式實際上要容易ggplot2
。
df %>%
gather(column, label) %>%
group_by(column, label) %>%
count()
# column label n
# <chr> <chr> <int>
# 1 colA label1 1
# 2 colA label3 1
# 3 colA label4 1
# 4 colA label5 1
# 5 colB label1 2
# 6 colB label4 2
# 7 colC label2 2
# 8 colC label3 1
# 9 colC label5 1
您可以輕松地將結果傳遞給ggplot2
df %>%
gather(column, label) %>%
group_by(column, label) %>%
count() %>%
ggplot(aes(label, n)) +
geom_col() +
facet_wrap(~column)
數據
df <- structure(list(colA = c("label1", "label3", "label4", "label5"
), colB = c("label1", "label1", "label4", "label4"), colC = c("label2",
"label3", "label2", "label5")), class = "data.frame", row.names = c(NA,
-4L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.