【问题标题】:R: plot : Adding labels to scatterplot points with varying number of decimal placesR:绘图:将标签添加到具有不同小数位数的散点图点
【发布时间】:2015-11-01 21:02:29
【问题描述】:

我正在尝试绘制一个散点图,其中每个点也有标签。标签是具有不同小数位数的数字。 我试过了:

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)

但标签未显示具有正确小数位数的数字。 感谢您的帮助。

【问题讨论】:

    标签: r plot rounding labels


    【解决方案1】:

    您可以使用formatC 对其中一种格式化函数进行矢量化。例如,沿螺旋线增加小数位数。

    ## 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'))
    

    【讨论】:

    • 感谢您的优雅回答。
    【解决方案2】:

    所以,我唯一改变的是在你的 text() 函数之外有格式函数。然后,我为 nsmall 添加了一个值,它表示您想要小数点右侧的位数。它现在应该可以工作了!当前示例在小数点右侧添加 3 位数字。

    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)
    

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2020-01-24
      相关资源
      最近更新 更多