[英]How to create stacked and grouped chart?
我正在嘗試按月創建一個包含兩列的條形圖,每列堆疊在一起。 對於每個月,第一列是視頻訪問總數,由 vid_new 和 vid_return 拆分。 第二列是電話訪問總數,由 phone_charge 和 phone_nocharge 拆分。
我仍然無法將條形並排正確。 此代碼使用第二張圖片中的數據框,它計算單詞“video”和“phone”的實例,而不是導致第三張圖片的 Count 列。
plot <- ggplot(data=new_df, aes(x=Month, y = count, fill = gen_type)) +
geom_bar(stat = "identity", position = "dodge")
下面是我正在使用的數據的圖片。 我已將其轉換為幾種不同的形式以嘗試新方法,但無法形成此圖。
如何在ggplot中按組和堆棧制作條形圖? 我需要什么數據結構才能實現?
預先感謝您的建議!
您可以嘗試這些選項中的任何一個,將您的數據重塑為 long 並創建和附加變量,以便您可以識別類型。 這里使用tidyverse
函數的代碼:
library(ggplot2)
library(dplyr)
library(tidyr)
#Date
df <- data.frame(Month=c(rep('Mar',4),rep('Apr',4),rep('May',2)),
spec_type=c('vid_new','vid_return','phone_charge','phone_nocharge',
'vid_new','vid_return','phone_charge','phone_nocharge',
'vid_new','vid_return'),
Count=c(7,85,595,56,237,848,2958,274,205,1079))
#Plot 1
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
mutate(Dup=spec_type) %>%
separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
ggplot(aes(x=Type,y=Count,fill=spec_type))+
geom_bar(stat = 'identity',position = 'stack')+
facet_wrap(.~Month,strip.position = 'bottom')+
theme(strip.placement = 'outside',
strip.background = element_blank())
輸出:
或這個:
#Plot 2
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
mutate(Dup=spec_type) %>%
separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
ggplot(aes(x=Type,y=Count,fill=spec_type))+
geom_bar(stat = 'identity',position = 'fill')+
facet_wrap(.~Month,strip.position = 'bottom',scales = 'free')+
theme(strip.placement = 'outside',
strip.background = element_blank())
輸出:
或這個:
#Plot 3
df %>% mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
mutate(Dup=spec_type) %>%
separate(Dup,c('Type','Class'),sep='_') %>% select(-Class) %>%
ggplot(aes(x=Type,y=Count,fill=spec_type))+
geom_bar(stat = 'identity',position = position_dodge2(preserve = 'single'))+
facet_wrap(.~Month,strip.position = 'bottom',scales = 'free')+
theme(strip.placement = 'outside',
strip.background = element_blank())
輸出:
為了按月查看,您可以使用facet_wrap()
並以智能方式放置標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.