den
den

Reputation: 169

ordering a variable for producing a simple plot

I face a difficulty while producing a simple plot with two curves overlayed. My variable on the x-axis represents weeks and therefore in would like to keep it ordered as in the dataframe figU5MR

  figU5MR
    Week U5MR CMR fWeek cWeek
 1    51  0.9 0.2    51    51
 2    52  0.2 0.2    52    52
 3    53  0.0 0.0    53    53
 4     1  0.0 0.0     1     1
 5     2  0.5 0.1     2     2
 6     3  0.2 0.0     3     3
 7     4  0.6 0.2     4     4
 8     5  0.2 0.2     5     5
 9     6  0.2 0.1     6     6
 10    7  0.2 0.0     7     7
 11    8  0.1 0.0     8     8
 12    9  0.1 0.0     9     9
 13   10  0.0 0.1    10    10
 14   11  0.0 0.0    11    11
 15   12  0.1 0.1    12    12
 16   13  0.0 0.0    13    13
 17   14  0.2 0.1    14    14
 18   15  0.1 0.0    15    15
 19   16  0.3 0.1    16    16
 20   17  0.3 0.1    17    17
 21   18  0.1 0.1    18    18
 22   19  0.3 0.1    19    19
 23   20  0.1 0.0    20    20

To do so i have first created an ordered factor fWeek. To plot the data i simply use the following which seems basic :

 plot( x=fWeek, y=U5MR, pch=24, cex=2,type="b", xlab="Weeks", xlim=c(-0.02,1.2), ylab="Death/10'000/day", main="Mortality rates per week",  axes=F)

 plot(x=fWeek,y=CMR,pch=19, cex=1.8,lty=1,type="o", gap=0, sfrac=0.005,  axes=T,   add=TRUE) 

The returned plot does not show the symbols as expected : enter image description here

To circumvent this i also tried to transform Week as a character cWeek : then the output is better but i lost the proper ordering of my weeks...weeks 51 to 53 appear at the complete end of the graph

Does anyone has an idea about how to get the right ordering of my weeks (as in image 1, while keeping the nice appearance of symbols as in picture 2? Sorry , i know this is basic but i can not get what i want, after hours searching.. Thanks!

Upvotes: 0

Views: 37

Answers (1)

IRTFM
IRTFM

Reputation: 263451

The printed output makes me think there is a dataframe that you have attached. Attaching dataframes is a BAD idea. Instead learn to use with which them allows you to grab the numericized rownames (assuming you haven't already put character values in there). Could also use 1:nrow(dfrm) to get a numeric sequence passed to y:

with(dfrm, plot( x=as.numeric(rownames(dfrm)), y=U5MR, pch=24, cex=2,type="b",
     xlab="Weeks", ylab="Death/10'000/day", main="Mortality rates per week",
     xaxt="n"))

Add back the axis with:

 axis(1, at=as.numeric(rownames(dfrm)), labels=dfrm$Week)

.. and leave out the xlim. That makes no sense (to me anyway)enter image description here.

Upvotes: 2

Related Questions