我尝试按月创建一个条形图,其中包括两列,每列都堆叠在一起。对于每个月,第一列是视频访问总数,按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中按组和按栈制作条形图?我需要什么样的数据结构来实现它?
提前感谢您的建议!
发布于 2020-10-12 05:07:32
您可以尝试这些选项中的任何一个,将您的数据重塑为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()并以一种智能的方式放置标签。
https://stackoverflow.com/questions/64308846
复制相似问题