我有两个类别变量,我想通过交叉列表进行比较。我做了一个扩展的正方形列联表的虚拟示例,其中X的类别在表的行中,而Y的类别序列在表的列中。该表总结了X和Y之间的关联。
表的对角线条目给出X类别与Y类别匹配的观察值的数量,在这种情况下,观察值为类别的命中数。每个非对角线条目对于X类别来说都是False Alarm,对于Y类别来说是Miss。
extended square contingency table
我想制作一个类似graph1的堆叠式barplot,它显示表格的每一行,并且填充的颜色来自列(Y变量)。最后两个栏显示每个类别的未命中和错误警报。
我设法制作了两个单独的图。下面的代码生成graph1的前四行。
,我将不胜感激。# Create Dummy Input sample.mtxx <- matrix(c(1,0,2,0,0,3,0,3,2,3,3,0,0,0,0,3), nrow = 4) categories <- c("A","B","C","D") colnames(sample.mtx) <- paste(categories) rownames(sample.mtx) <- paste(categories) # Change from wide to long format g1.df <- melt(sample.mtx) # Zero sizes were causing problem so I removed them. g1.df <- g1.df[g1.df$value!=0,] # Add a label column to show "Hit". g1.df$label <- ifelse(g1.df$Var1==g1.df$Var2, "Hit", as.character("")) # Plotting plot1 <- ggplot(data=g1.df, mapping=aes(fill=Var2, y=value, x=Var1, label = label))+ geom_bar(width = 0.6, position="stack", stat="identity")+ labs(x="Table Feature", y="Entry size as the number of observations", title="Entry Size") + geom_text(size = 4, position = position_stack(vjust = 0.5))+ coord_flip()+ theme_bw()+ scale_x_discrete(limit = c("D", "C", "B", "A"))+ scale_y_discrete(limits=seq(0,10,1))+ theme(plot.title = element_text(family = "Times", color = "#353535", face = "bold", size = 12, hjust = 0.5))+ theme(legend.position = "bottom", legend.title = element_blank())+ theme( panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank() )
Plot1显示结果。问题是堆叠的条中的组件顺序不正确。如果有人可以解释我如何安排酒吧的组成部分?
要绘制未命中和错误警报,这就是我写的内容:
# Hits, False Alarm, and Miss hits <- diag(sample.mtx) false.alarms <- rowSums(sample.mtx) - hits misses <- colSums(sample.mtx) - hits # Make a data frame g1.df1 <- as.data.frame(cbind(categories, misses, false.alarms)) # Change it to long format and get rid of zero sizes. g1.df1.m <- melt(g1.df1, id.vars="categories") g1.df1.m <- g1.df1.m[g1.df1.m$value!=0,] # Plotting plot2 <- ggplot(data=g1.df1.m, inherit.aes = FALSE, mapping=aes(fill=categories, y=value, x=variable))+ geom_bar(width = 0.6, position="stack", stat="identity")+ coord_flip()+ theme_bw()+ theme(legend.position = "none")+ scale_x_discrete(limit = c("misses", "false.alarms"))+ scale_y_discrete(limits=seq(0,10,1))
plot2我对这个情节感到满意。但是我想要的是在一个绘图中同时包含plot1和plot 2,如图1所示。任何人都可以提供有关如何从不同数据框中绘制堆叠条形图的指南。还是有更好的方法来制作graph1。
我有两个类别变量,我想通过交叉列表进行比较。我做了一个扩展的正方形列联表的虚拟示例,其中X的类别在表的行中,...
[如果您只想用代码重现Graph1
,则部分起作用: