如何显示具有较大价值差异的绘图数据?

时间:2016-06-22 15:53:23

标签: r plot ggplot2

我正在使用car_crashes绘制数据ggplot。它有3种不同的数据集,如下所示 enter image description here

但由于汽车的平均值很大,其他值甚至没有显示,因为它们在100的范围内。如果我删除汽车数据的平均值,情节实际上看起来像这样 enter image description here

有没有办法可以在一个图中显示所有数据,这样至少我可以看到崩溃的数量? 我使用的代码如下:

carcrashes_figure <- ggplot()+geom_area(aes(YEAR_WW,AverageofCars,group = 1,colour = 'Average of cars'),car_crashes,fill = "dodgerblue1",alpha = 0.4)+
  geom_line(aes(YEAR_WW,averageofcars,group = 1,linetype ='num of crashes'),car_crashes,fill = "dodgerblue3",colour = "dodgerblue3",size = 1.6) +
  geom_line(aes(car_crashes$YEAR_WW,constantline,group = 1, size = 'constant line' ),car_crashes1,fill = "green4",colour = "green4")+
  theme_bw() +
  theme(axis.text.x  = element_text(angle=70, vjust=0.6, face = 'bold'))+
  theme(axis.text.y  = element_text(angle=0, vjust=0.2, face = 'bold'))+
  scale_colour_manual('', values = "dodgerblue1")+
  scale_size_manual('',values = 1.4)+
  scale_linetype_manual('',values = 1)+
  scale_y_continuous()+
  theme(legend.text = element_text(size = 8, colour = "black", angle = 0)) 
carcrashes_figure

1 个答案:

答案 0 :(得分:0)

我同意了这个想法,使用@Jim Quirk的单独y轴。据我所知,ggplot2不是很擅长这样做,所以我使用了基本情节。

# making example ts_data
set.seed(1); data <- matrix(c(rnorm(21, 1000, 100), rnorm(21, 53, 10), rep(53, 21)), ncol=3)
ts_data <- ts(data, start = 1980, frequency = 1)

par(mar=c(4, 4.2, 1.5, 4.2))              # enlarge a right margin
# plot(ts_data[,1])                       # check y-range
plot(ts_data[,2:3], plot.type = "single", ylab="num of crashes & constant line", 
     col=c(2,3), ylim=c(35,100), lwd=2)   # draw "num of crashes" and "constant line"
par(usr = c(par("usr")[1:2], 490, 1310))  # set the second y coordinates
axis(4)                                   # write it on the right side
polygon(x = c(1980:2000, rev(1980:2000)), y = c(ts_data[,1], rep(0,21)), 
        col="#0000FF20", border = "blue") # paint "Average of cars"
mtext(side=4, "Average of cars", line=2.5)
legend("topright",paste(c("num of crashes","constant line","Average of cars")),
   pt.cex=c(0,0,3), lty=c(1,1,0), pch=15, cex=0.9, col=c(2, 3, "#0000FF20"), bty="n", 
   inset=c(0.02,-0.02), y.intersp=1.5)

enter image description here