R - 使用y-scale绘制条形图以使用ggplot

时间:2016-05-24 18:41:18

标签: r ggplot2 bar-chart scaletransform

我需要一个条形图,显示每个值的条形图(即使该值为0.0002)。保持ylim与其他类似的条形图进行比较也很重要。允许缩放ylim,但保持符号很重要。任何帮助都将非常感激。

data <- c(
0.0224544949, 0.040071356,  0.005862310,
-0.0024304989, 0.025612782,  0.004551214,
-0.0021313240, 0.026042635,  0.004003015,
-0.0070571818, 0.001242457, -0.006225233,
0.0001473911, 0.052633570,  0.039935131)

bias <- matrix(data,5,3, byrow=TRUE)
colnames(bias) <- c("H=0.55","H=0.75","H=0.95")
rownames(bias) <- c("M1","M2","M3","M4","M5")

dat1 <- data.frame(
Method = factor(c("M1","M2","M3","M4","M5")),
H = factor(c(rep(c("H=0.55"),5),rep(c("H=0.75"),5),rep(c("H=0.95"),5)  ), levels=c("H=0.55","H=0.75","H=0.95")),
Bias = c(bias[,1],bias[,2],bias[,3])
)


name <- paste("Parameter bias")

ggplot(data=dat1, aes(x=H, y=Bias, fill=Method)) +
        geom_bar(stat="identity", position=position_dodge()) +
        ggtitle(name) +     
        theme_bw() +
    scale_y_continuous(limits = c(-0.03,0.03)) 

1 个答案:

答案 0 :(得分:0)

如果您真的担心没有出现小值,那么您可以使用geom_errorbarh()在某些水平误差条上进行粘贴。

以下是一个例子:

#Slightly updated data, made M5, H=0.55 even smaller so that it doesnt appear in normal plot
data <- c(
  0.0224544949, 0.040071356,  0.005862310,
  -0.0024304989, 0.025612782,  0.004551214,
  -0.0021313240, 0.026042635,  0.004003015,
  -0.0070571818, 0.001242457, -0.006225233,
  0.00001473911, 0.052633570,  0.039935131)

bias <- matrix(data,5,3, byrow=TRUE)
colnames(bias) <- c("H=0.55","H=0.75","H=0.95")
rownames(bias) <- c("M1","M2","M3","M4","M5")

dat1 <- data.frame(
  Method = factor(c("M1","M2","M3","M4","M5")),
  H = factor(c(rep(c("H=0.55"),5),rep(c("H=0.75"),5),rep(c("H=0.95"),5)  ), levels=c("H=0.55","H=0.75","H=0.95")),
  Bias = c(bias[,1],bias[,2],bias[,3])
)

您当前的方法会给出:

ggplot(data=dat1, aes(x=H, y=Bias, fill=Method)) +
  geom_bar(stat="identity", position=position_dodge(width=0.9),width=0.9) +
  ggtitle(name) +     
  theme_bw()

enter image description here

在上面你可以清楚地看到H=0.55, M5因为它太小而没有出现。但是,它仍在绘制。

现在添加误差条我们可以使它成为一个小条子,以便我们知道它被绘制。

ggplot(data=dat1, aes(x=H, y=Bias, fill=Method)) +
  geom_bar(stat="identity", position=position_dodge(width=0.9),width=0.9) +
  ggtitle(name) +     
  theme_bw()+ geom_errorbarh(aes(xmax=as.numeric(H)+0.45,xmin=as.numeric(H)-0.45,height=0,color=Method),position=position_dodge(width=0.9))

给出了:

enter image description here

注意:我删除了ylim代码,因为它删除了一些数据。只需使用+scale_y_continuous(limits = c(-0.03,0.03))

将其添加到上面的代码中就足够了