R新手在这里。我正在尝试创建多个图,如附带的屏幕截图所示:
(图表只是模型)但使用ggplot / xyplot遇到了困难。
我的目标是创建多个图表,这样我们就可以比较每个月/年的趋势,并在每个部门的图表上单独划分。我的数据集目前包含以下列:利润,部门,年份,月份。有多行包含每个部门/年/月的利润值,我需要对其进行分组和平均。
我发现最接近这样做的是使用下面的ggplot,但我现在的代码不允许我为不同年份的各个部门和多个图表获取多行图表。应该可以做到这一点,但谷歌搜索引导我圈出ggplot是否是正确的选择。
e.g。
ggplot(deptProfit,aes(x=Month,y=Profit))+
stat_summary(fun.y=mean,geom="line",color="blue",linetype=2)+
stat_summary(fun.y=mean,geom="point", pch=1,size=3)+
scale_x_continuous(breaks=deptProfit$Month)+
facet_grid(~Region)+
theme_bw()
打开有关如何在屏幕截图中创建图表的任何建议。谢谢!
示例数据:
Region=c(1,1,1,1,2,2,2,2,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,2,2)
Year= c(2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2014,2014,2015,2015,2016,2016,2014,2014,2015,2015,2016,2016,2017,2017)
Dept= c(sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing,sales,marketing)
Profit =c(16,24,29,24,41,51,71,66,78,73,88,117,23,23,25,28,65,51,54,44,49,66,76,94,20,18,25,25,24,17,69,56)
月= c(9,12,9,7,4,1,5,5,9,6,3,3,7,10,7,9,7,7,7,12,4,1 ,8,6,5,7,5,3,9,6,10,8)
答案 0 :(得分:0)
你快到了。如果我理解正确,我认为你不需要stat_summary
。
这里有很多缺失的数据,但希望这是一个开始:
首先创建数据框deptProfit
:
deptProfit <- data.frame(Region=c(1,1,1,1,2,2,2,2,0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,2,2),
Year= c(2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2017,2017,2013,2013,2014,2014,2015,2015,2016,2016,2014,2014,2015,2015,2016,2016,2017,2017),
Dept= c("sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing","sales","marketing"),
Profit =c(16,24,29,24,41,51,71,66,78,73,88,117,23,23,25,28,65,51,54,44,49,66,76,94,20,18,25,25,24,17,69,56),
Month = c(9,12,9,7,4,1,5,5,9,6,3,3,7,10,7,9,7,7,7,12,4,1,8,6,5,7,5,3,9,6,10,8))
现在我们可以绘制:
library(ggplot2)
ggplot(deptProfit,aes(x=Month, y=Profit, color = Dept))+
geom_line(linetype = 2) +
geom_point(pch = 1, size = 3) +
scale_x_continuous(breaks=1:12)+
facet_grid(Year ~ Region)+
theme_bw()
在上文中,我们将Dept
映射到color
美学,因此它们将分别绘制。现在美学已正确映射,我们可以调用geom_line
和geom_point
。最后,使用facet_grid
,我们可以设置水平(Year
)和垂直(Dept
)类别。
这应该给你以下内容: