首页 > 解决方案 > 用条形图叠加条形图

问题描述

我想用条形图叠加条形图,并在 xyplot 中使用面板参数,但它不起作用。它不绘制任何内容并发出许多警告,例如:

1: In order(as.numeric(x)) : NAs introduced by coercion
2: In diff(as.numeric(x[ord])) : NAs introduced by coercion

代码在这里,但是它与阶乘 Alternatece 和 Subject 变量一起使用,尽管它以水平方式绘制条形图:

t2 <- data.frame(Alternative = c("FA", "HF", "NO", "HF", "FA", "NO"), 
  AlloOthe = c(50, 80, 20, 80, 80, 20), 
  Subject = rep(c("2001", "2002"), each = 3)
)
t2$Alternative <- as.character(t2$Alternative)
t2$Subject <- as.character(t2$Subject)
library(lattice)
xyplot(AlloOthe ~ Alternative | Subject, data = t2,
  panel = function(x, y) {
    panel.barchart(x, y)
    panel.stripplot(x, y, type = c("p", "l"))
  },
  ylab = "Allocation to Other"
)

那么有没有人可以向我展示正确的代码或让它在正确的数据上工作?非常感谢!

标签: rpanellattice

解决方案


我不是lattice包装方面的专家,但我通过这篇文章得到了你的情节:Add stripplot points to bwplot (Lattice graphics in R),所以,我添加...到面板函数定义中,并且我也替换xyplotbarchart.

所以,基本上,它看起来像:

# Assigning Alternative and Subject as factor
t2$Alternative = as.factor(t2$Alternative)
t2$Subject = as.factor(t2$Subject)

library(lattice)
barchart(AlloOthe ~ Alternative | Subject, data = t2,
         panel = function(x,y,...) {
           panel.barchart(x,y,col=adjustcolor("darkorchid",alpha=.6),...)
           panel.stripplot(x,y,col="lightseagreen",pch=16,size=3,...)
         },
         ylab = "Allocation to Other")

情节看起来像:

在此处输入图像描述

作为替代方案,您可以ggplot通过执行以下操作来使用:

library(ggplot2)
ggplot(t2, aes(x = Alternative, y = AlloOthe, group = Alternative)) +
  facet_grid(.~Subject) +
  geom_bar(stat = "identity", fill = adjustcolor("darkorchid", alpha = 0.6)) +
  geom_point(size = 3, color = "lightseagreen") +
  ylab("Allocation to Other")

情节看起来像:

在此处输入图像描述

希望对你有帮助!


推荐阅读