R:两轴图表调整

时间:2013-06-27 14:36:25

标签: r plot bar-chart multiple-axes

我正在尝试用两个轴绘制聊天,这里是代码,附图是情节,

我必须对它做两次调整。

  • 我想绘制一条带点的线条,点应该是条形的中间
  • 调整右侧轴(即轴(4))刻度线应与左侧轴(即轴(2))对齐

代码:

Region=c("North","South","East","West")
Sales=sample(500:1000,4)
Change=sample(1:10,4)/10
names(Sales)=Region
names(Change)=Region
barplot(Sales,ylim=c(0,1000))
par(new=T)
plot(Change,type="b",axes=F,ylim=c(0,1))
axis(4)
box()

此致

大行善者

2 个答案:

答案 0 :(得分:0)

首先,将条形图保存为某个对象。所以你将得到中间点的坐标。然后,要添加行,您还可以使用函数lines(),并将Change值乘以1000。 然后,axis()函数提供at=值和labels=at=相同,只需除以1000。

x<-barplot(Sales,ylim=c(0,1000))
lines(x,Change*1000,type="b")
axis(4,at=seq(0,800,200),labels=seq(0,800,200)/1000)

enter image description here

答案 1 :(得分:0)

您需要播放以在第二个图中设置相同的x轴,您可以从par("usr")获取此信息。 xaxs="i"是准确设置xlim,默认情况下,R会稍微增加xlim以使其更好看。

par(mar=c(5,5,2,5)) # change margins
x = barplot(Sales, ylim=c(0,1000)) # barplot, keep middle points of bars
mtext("Sales", 2, line=3) # first y-axis label
xlim = par("usr")[1:2] # get xlim from plot
par(new=TRUE) 
plot.new() # new plot
plot.window(xlim=xlim, ylim=c(0,1), xaxs="i", yaxs="i") # new plot area, same xlim
lines(x,Change,type="b") # the lines in the middle points
axis(4) # secondary y-axis
mtext("Change", 4, line=3) # secondary y-axis label
box()

the plot