r - 获得闪避条形图?

标签 r graph ggplot2

我刚刚看到这段代码可以让我绘制多个纵坐标(我知道这在社区中是一个坏主意,但我需要这样做来比较不同的指标)。由于这不能在 ggplot2 中固有地完成,我想知道我是否可以调整以下代码来完成我需要的事情:

twoord.plot(2:10,seq(3,7,by=0.5)+rnorm(9),
  1:15,rev(60:74)+rnorm(15),xlab="Sequence",
  ylab="Ascending values",rylab="Descending values",
  main="Plot with two ordinates - bars on the left",
  type=c("bar","l"),lcol=3,rcol=4)

绘制以下内容:

enter image description here

我正在寻找的是并排绘制多个条形图。我尝试用 type=c("bar", "bar") 替换 type=c("bar", "l") 但这给了我重叠的条。我想要绘制的确切数据如下:

Category    SubCat  Value
A           Cat1    0.1
B           Cat1    0.2
A           Cat2    0.3
B           Cat2    0.24
A           Cat3    13
B           Cat3    41
A           Cat4    60
B           Cat4    146

我希望 (Cat1,Cat2) 下的 (A,B) 的刻度在左边,(A,B) 在 (Cat3, Cat4) 下的刻度在右边,A 和 B 下的所有条形图分别分组在一起。有人可以告诉我该怎么做吗?

最佳答案

以下内容可能与您将要使用 ggplot2 的内容接近:

d <- read.table(textConnection("Category    SubCat  Value
A           Cat1    0.1
B           Cat1    0.2
A           Cat2    0.3
B           Cat2    0.24
A           Cat3    13
B           Cat3    41
A           Cat4    60
B           Cat4    146"),header = TRUE, sep="")

d$grp <- rep(c('Cat1 - Cat2','Cat3 - Cat4'), each = 4)
ggplot(d,aes(x = Category, y = Value)) + 
    facet_wrap(~grp, scales = "free_y") + 
    geom_bar(aes(fill = SubCat), position = "dodge")

enter image description here

这通过分面并允许 ggplot2 单独设置轴来实现“双 y 轴”。我确信使用基本图形可以获得更接近您想要的东西,但这需要更多考虑。

编辑

这是使用 twoord.plot 的技巧。花了很多时间摆弄,但我从未使用过该功能,所以可能有更简单的方法:

par(xaxt = "n") 
twoord.plot(ly = d$Value[1:4],ry = d$Value[5:8], rx = c(9,11,13,15), lx = c(1,3,5,7),
            type = c('bar','bar'), 
            xlim = c(0,16),
            lylim = c(0,0.35),rylim = c(12,150))
par(xaxt="s")           
axis(1, at = c(1,3,5,7,9,11,13,15),
        labels = paste(d$Category,d$SubCat,sep=""),
        las = 3)

enter image description here

关于r - 获得闪避条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7170208/

相关文章:

r - R 中的 tryCatch 在出错时执行

r - 根据 R 中字符串变量的部分匹配进行过滤

r - 在图上添加回归线方程和 R^2

r - 语句不在函数内执行,独立执行

javascript - 交互式数据表 : keep column filters after rerendering the table

r - 如何在 R 中调整树状图输出的大小

java - 用 Java 绘制 X-Y 图

graph - 在无向图中查找具有特定成本的路径

algorithm - Cormen WreSTLer 的竞争 BFS

r - 在 R 图中使用图像作为区域填充