基础r中的折线图叠加条形图 [英] Line Graph Overlaying bar graph in base r

查看:56
本文介绍了基础r中的折线图叠加条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面编写了以下代码.我想用线图覆盖条形图.我拥有的代码可以完成所有工作,但只有一个问题.我希望折线图上的点位于条形图的中心,即它们应该向左移动一点.我在哪里想念它?如果这也可以在ggplot中完成,我也会很高兴.但即使以r为底

I have written the following code below. I would like to overlay a bar graph with a line graph. The code I have does it all but with just one problem. I would like the points on the line graph to be in the center of the bar graph, i.e. they should shift to the left a little bit. where Im I missing it? If this can be done in ggplot as well I would be happy too. but even base r would do

par(mai = c ( 1 , 2, 1, 1), omi = c(0, 0, 0, 0))
yy <- c(31,31,31,50,50,61,69,75,80,88,94,101,108,115,121,124,125,125,125,126,127)
name1 <- c ("15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35")
xx <- barplot(yy, ylab = "", names.arg = name1, ylim = c(0, 140),col="steelblue")
text(xx, yy + 3, labels = as.character(yy),srt=45)
mtext(2,text="",line=2)
par(new = T)
xx2 <- c(15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35)
yy2 <-   c(379,474,579,725,922,1181,1473,1846,2316,2962,3688,4786,6069,7605,9504,10680,11074,11074,11074,11483,11484)
plot(xx2, yy2, xlim = c(14, 36), ylim = c(0, 14000),type ="n" , axes = F, xlab ="",  ylab ="",col="blue",main="")
lines(xx2, yy2, lwd = 2,col="red",lty=1)
points(xx2, yy2, pch = 18, cex = 1,col="red")
text(xx2, yy2 + 4 , labels = as.character(yy2),srt=90)
par(new = T)
par(mai = c ( 1 , 1, 1, 1))
axis(2)
mtext(2,text="",line=2.5)
mtext("",side=1,col="black",line=2)
grid()

推荐答案

问题是由于两个图的边距不同,您具有不同的x比例.

The problem is that you have different x scale due to the different margins of the two plots.

除非您想手动找到xx2,否则要考虑的另一种解决方案是改用右y轴.

Unless you want to find xx2 by hand... another solution to consider is to use a right y axis instead.

yy <- c(31,31,31,50,50,61,69,75,80,88,94,101,108,115,121,124,125,125,125,126,127)
name1 <- c ("15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35")
xx <- barplot(yy, ylab = "", names.arg = name1, ylim = c(0, 140),col="steelblue")
text(xx, yy + 3, labels = as.character(yy),srt=45)
mtext(2,text="",line=2)
par(new = T)
yy2 <-   c(379,474,579,725,922,1181,1473,1846,2316,2962,3688,4786,6069,7605,9504,10680,11074,11074,11074,11483,11484)
plot(xx+0.5, yy2, "l", lwd = 2,col="red",lty=1, 
     axes=F, ylim=c(0, 14000), xlim=c(min(xx), max(xx)+1))
points(xx+0.5, yy2, pch = 18, cex = 1,col="red")
axis(4)
text(xx+0.5, yy2 + 4 , labels = as.character(yy2),srt=90)

这篇关于基础r中的折线图叠加条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆