我刚刚看到这段代码可以让我绘制多个纵坐标(我知道这在社区中是一个坏主意,但我需要这样做来比较不同的指标)。由于这不能在 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)
绘制以下内容:
我正在寻找的是并排绘制多个条形图。我尝试用 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")
这通过分面并允许 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)
关于r - 获得闪避条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7170208/