2013-06-27 83 views
1

我想繪製一個與兩軸聊天,這裏是代碼和附加的情節,R:雙軸圖表調整

我必須做兩個調整。

  • 我要繪製用點和點的線應杆
  • 調整右側軸的中間(即,軸(4))的刻度標記應與左側axix對齊(即軸(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() 

問候,

大行善者

回答

0

首先,將您的barplot保存爲某個對象。所以你會得到中間點的座標。然後添加行,你可以使用也起到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

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