简体   繁体   中英

R plot: how to make a histogram with horizontal lines using plot()

How can I use plot to turn this plot sideways so the histogram bars are horizontal?

size<- abs(rnorm(20,10,10))
age<-c(seq(1, 20, by=2))
plot(size~age, type=("n")); lines(size~age, type=c("l"), lines(size~age, type=c("h")))

在此输入图像描述

What I want is roughly something like this, with the histogram lines horizontal:

在此输入图像描述

which I did with

plot(size~age, type=("n"), yaxt="n", xaxt="n", ylab=""); lines(size~age, type=c("l"), lines(size~age, type=c("h"))); axis(4); axis(1,las=2)

and then rotating the image output in other software.

I'd like to know how I can use the plot function to get the output plot sideways so I can make groups of them in R without having to rotate them outside of R .

UPDATE Thanks to the very helpful suggestion from @csgillespie I've got this, which has got me on my way:

size<- abs(rnorm(20,10,10)) 
age<-c(seq(1, 40, by=2)) # sorry for the typo in the first set of example data above
plot(-age~size, type="n",yaxt="n", ylab="Age", xlab="Size")
lines(-age~size)
segments(0, -age, size, -age)
axis(2, labels=c(seq(0,max(age), by=5)), at=-c(seq(0,max(age), by=5)), las=1) # this is a more general approach to labelling the axis ticks

and here's resulting plot (not pretty yet, but I think I can do the rest from here):

在此输入图像描述

You can get what you want by using -age then adding the scale manually.

plot(-age~size, type="n",yaxt="n", xlab="", ylab="Age")
lines(-age~size)
segments(0, -age, size, -age)
axis(2, labels=c(0,5,10,15,20), at=-c(0,5,10,15,20), las=1)

The code above produces an identical plot to you example figure, except, the y-axis label has been rotated. If you want the y-axis label to be rotated, then use ylab="" in the plot command and add it manually with text

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM