改变ggplot2中的Y轴断点

时间:2014-03-06 12:48:39

标签: r bar-chart

我有这段代码给出如下图表:

d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) + 
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)))

我只关心最后一行。在图中,y轴仅从-3到2.5。我如何从-3.5到3.5得到它甚至是?

我确定我犯了一个简单的错误,但无法解决它!

enter image description here非常感谢提前。

1 个答案:

答案 0 :(得分:4)

你快到了。尝试设置限制。

d=ggplot(df, aes(x=Year, y=NAO_Index, width=.8)) +
+ geom_bar(stat="identity", aes(fill=NAO_Index>0), position='identity', col = 'transparent') +
+ theme_bw() + scale_fill_manual(values=c("royalblue", "firebrick3"), name="NAO Oscillation", labels=c("Negative", "Positive"), guide=guide_legend(reverse=TRUE)) +
theme(legend.position=c(0.06, 0.92)) + 
+ theme(axis.title.x=element_text(vjust=-0.2)) +
+ geom_line(data=dfmoveav, aes(x=Year ,y=moveav)) +
+ ylab("NAO Index") +
+ ggtitle("NAO Index between 1860 and 2050") +
+ scale_x_continuous(breaks=c(seq(1860,2050,10))) +
+ scale_y_continuous(breaks=c(seq(-3.5,3.5,0.5)), limits = c(-3.5, 3.5))

有关它的更多信息here

要将线条映射到图例,您应该将变量映射到美学。但这不是微不足道的,你会找到避免这种方法的参考。

df <- data.frame(year=factor(seq(1:10)),
                 nao = rnorm(10, 0, 2),
                 mov = rnorm(10, 0,3))
df2 <- data.frame(year=factor(seq(1:10)),
                  mov = df$nao+rnorm(10, 0, 0.1),
                  g = .1)
ggplot() +
  geom_bar(data = df, aes(x=year, y=nao, fill=nao > 0), width=.8, 
           stat="identity", position ='identity', col = 'transparent') +
  geom_line(data = df2, aes(x = year, y = mov, group = g, size = g)) +
  scale_fill_manual(values=c("royalblue", "firebrick3"),
                    name="NAO Oscillation",
                    labels=c("Negative", "Positive"),
                    guide=guide_legend(reverse=TRUE)) +
  scale_size('Trend', range = 1, labels = 'Moving\naverage') +
  ggtitle("NAO Index between 1860 and 2050") +
  scale_y_continuous(breaks=c(seq(-5,5,0.5)), limits = c(-5, 5)) +
  ylab("NAO Index") +
  theme(legend.position = c(0.07, 0.80),
        axis.title.x = element_text(vjust= -0.2),
        legend.background = element_blank())

ggplot bar and line

这可能不是将变量映射到美学的最佳方法。