我正在尝试使用ggplot2
创建带有多个分组条形图的图表。在我的数据集中,我需要选择三列,以便根据我绘制的这张草图对图表进行分组:
代码:
library(dplyr)
library(tidyr)
library(ggplot2)
DOPTransformationsMean %>%
select(SPL, AddedFields, ModifiedFields, RemovedFields) %>%
gather(Var,Val,-SPL) %>%
ggplot(aes(SPL, Val, group = Var)) +
ylab("Quantity") +
geom_bar(stat="identity", width = 0.3) +
scale_fill_manual(values=c("solid", "solid", "solid")) +
scale_color_manual(labels = c("Added Fields", "Modified Fields", "Removed Fields"), values=c('#b30000','#00b300','#00b3b3')) +
theme_bw(base_size = 30) +
theme(plot.title = element_text(hjust = 0.5), legend.title=element_blank(),legend.position = "bottom", legend.text=element_text(size=27), legend.direction="vertical") +
scale_y_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))
代码结果:
数据集:
SPL,AddedClasses,ModifiedClasses,RemovedClasses,AddedMethods,ModifiedMethods,RemovedMethods,AddedImports,RemovedImports,AddedFields,ModifiedFields,RemovedFields
Reminder-PL,49,76,0,99,78,1,43,0,62,0,2
Iris-PL,84,21,4,14,8,0,34,0,2,0,0
我遵循了类似的example,可以生成折线图,但是通过对数据集进行分组,我无法将条形进行分组。
答案 0 :(得分:2)
您必须告诉ggplot
根据图的aes
部分中的组填充条形图。
DOPTransformationsMean %>%
select(SPL, AddedFields, ModifiedFields, RemovedFields) %>%
gather(Var,Val,-SPL) %>%
ggplot(aes(SPL, Val, group = Var, fill = Var)) +
ylab("Quantity") +
geom_bar(stat="identity", width = 0.3, position = "dodge") +
scale_fill_manual(labels = c("Added Fields", "Modified Fields", "Removed Fields"),
values=c('#b30000','#00b300','#00b3b3')) +
theme_bw(base_size = 30) +
theme(plot.title = element_text(hjust = 0.5), legend.title=element_blank(),
legend.position = "bottom", legend.text=element_text(size=27),
legend.direction="vertical") +
scale_y_continuous(breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))