2

I am trying to plot a chat with two axis, here is the code and attached is the plot,

I have to do two adjustments to it.

  • I want to plot a line with dots and dots should be middle of the bars
  • Adjusting right side axis(i.e axis(4)) tick marks should align with left side axix(i.e axis(2))

Code:

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()

Regards,

Sivaji

Ricardo Oliveros-Ramos
  • 4,322
  • 2
  • 25
  • 42
Sivaji
  • 164
  • 9

2 Answers2

0

First, save your barplot as some object. So you will get coordinates of the middle points. Then to add line you can use also function lines() and just multiply Change values with 1000. Then for axis() function supply at= values and labels= the same as at=, just divided by 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

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
0

You need to play to set the same x-axis in the second plot, you get this info from par("usr"). The xaxs="i" is to set the xlim exactly, by default R increase the xlim a bit to make it better looking.

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

Ricardo Oliveros-Ramos
  • 4,322
  • 2
  • 25
  • 42