简体   繁体   中英

R: plot : Adding labels to scatterplot points with varying number of decimal places

I am trying to plot a scatterdiagram that also has labels for each point. The labels are numbers with varying numbers of decimal places. I tried:

x1=c(1:5)
y1=c(1:5)

round1 <- c(1,2,1,3,4)
df <- data.frame(x1,y1,round1)
df

plot(x=df$x1,y=df$y1)
text(df$x1, df$y1, labels=format(round(df$y1,df$round1)) , cex= 0.7, pos=3)

But the labels are not showing the numbers with the correct number of decimal places. Thanks for your help.

You can vectorize one of the formatting functions, here with formatC . Increasing number of decimal places along the spiral, for example.

## Some data
theta <- seq(-2*pi, 2*pi, length=100)
round1 <- rep(1:5, each=20)
dat <- data.frame(x=cos(theta)*exp(.2*theta), y=sin(theta)*exp(.2*theta), round1=round1)

plot(dat[1:2], type="l", pch=20)
inds <- seq(1, 100, by=5)  # only add labels at a few points
text(dat[inds,1:2],
     labels=Vectorize(formatC)(dat$x[inds], digits=dat$round1[inds], format='f'))

在此处输入图片说明

So, the only thing I changed was to have the format function outside of your text() function. Then, I added a value to nsmall, which represents how many digits you want to the right of your decimal point. It should work now! The current example adds 3 digits to the right of your decimal point.

x1=c(1:5)
y1=c(1:5)

round1 <- c(1,2,1,3,4)

## Assign how many digits you want to digits:
digits=3
round1 <- format(round(round1,digits),nsmall=digits)

df <- data.frame(x1,y1,round1)
df
plot(x=df$x1,y=df$y1)

# Changed the labels to directly reference round1 vector
text(df$x1, df$y1, labels=round1 , cex= 0.7, pos=3)

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