开发者

How can I plot a 1-D plot in R?

开发者 https://www.devze.com 2023-01-17 11:31 出处:网络
I have a vector of integers, e.g.: 2,8,11,19. I would like to plot a line of开发者_如何学C length e.g. 20 then plot a dot for each value that exist in the list (at some constant height), so I get som

I have a vector of integers, e.g.: 2,8,11,19.

I would like to plot a line of开发者_如何学C length e.g. 20 then plot a dot for each value that exist in the list (at some constant height), so I get something like this:

-+-----+--+-------+-


library(lattice)


x <- c(2, 8, 11, 19)
stripplot(x)

you can adjust the scales to your liking. see ?stripplot


Brandon Bertelsen is really close...

x <- c(2,8,11,19)
x <- data.frame(x,1) ## 1 is your "height"
plot(x, type = 'o', pch = '|', ylab = '')

But I wrote this mostly to mention that you might also in base graphics look at stripchart() and rug() for ways to look at 1-d data.


This can be done using ggplot2 by removing all the axis and plotting on a constant y value. You can then use the usual ggplot2 functions to change the colours of the dots, and annotate with text, more lines etc.

How can I plot a 1-D plot in R?

library(ggplot2)

x=c(2,8,11,19)

ggplot(data.frame(x), aes(x=x, y=0)) +
  geom_point(size = 10)  +
  annotate("segment",x=1,xend=20, y=0, yend=0, size=2) +
  annotate("segment",x=1,xend=1, y=-0.1,yend=0.1, size=2) +
  annotate("segment",x=20,xend=20, y=-0.1,yend=0.1, size=2) +
  geom_text(aes(label = x), col="white") +
  scale_x_continuous(limits = c(1,20)) +
  scale_y_continuous(limits = c(-1,1)) +
  scale_color_manual(values = unname(colours)) + 
  theme(panel.background = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.title = element_blank())

This plot is essentially a straight line centered around 0 with two more line segments added at the ends as stoppers. annotate("segment",...) is preferential to a reference line as you can control how long the line is drawn.


With the base graphics:

x <- c(2,8,11,19)
x <- data.frame(x,1) ## 1 is your "height"
plot(x, type="b")


This may be helpful for those plotting one-dimensional ordinal data.

x<-c(-1.5,2,2.5,-2,.05)
## Make y-value=0
x<-cbind(x,0)
## Plotting without box or axis with dot, representing data points                  
plot(x,bty='n',xaxt='n',yaxt='n',ylab='',xlab='',pch=21,cex=2)

## Placing axis at y-value in order to pass through points with sequence wider than range
axis(side=1,seq(-4,4,1),pos=0)  ## Using y-value as position 

## Placing x-values & x-axis label onto plot
text(x,labels=x[,1],pos=3,offset=1,font=2)
text(y=0,x=0,labels='One-Dimensional Plot',pos=1,offset=3,font=2)


Interestingly, nobody has mentioned stripchart

stripchart(x, pch = "+")

You can use add = TRUE to add the stripchart to an existing plot, and the at parameter to define the y value at which to plot your data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号