R legend pch mix of character and numeric

前端 未结 5 1349
忘掉有多难
忘掉有多难 2020-12-31 04:28

Is it possible to use a mix of character and number as plotting symbols in R legend?

plot(x=c(2,4,8),y=c(5,4,2),pch=16)
points(x=c(3,5),y=c(2,4),pch=\"+\")
l         


        
相关标签:
5条回答
  • 2020-12-31 04:48

    As noted in previous answers, you can simply add the numerical equivalent of the numeric and character symbols you want to plot.

    However, just a related aside: if you want to plot larger numbers (e.g., > 100) or strings (e.g., 'ABC') as symbols, you need to use a totally different approach based on using text().

    `Plot(x,y,dat,type='n') ; text(x,y,labels = c(100,'ABC')
    

    Creating a legend in this case is more complicated, and the best approach I've ever come up with is to stack legends on top of each other and using the legend argument for both the pch symbol and the description:

    pchs <- c(100,'ABC','540',sum(13+200),'SO77')
    
    plot(1:5,1:5,type='n',xlim=c(1,5.1))
      text(1:5,1:5,labels = pchs)
      legend(3.5,3,legend = pchs,bty='n',title = '')
      legend(3.5,3,legend = paste(strrep(' ',12),'ID#',pchs),bty='n',title='Legend')
      rect(xleft = 3.7, ybottom = 1.5, xright = 5.1, ytop = 3)
    
    • This uses strrep to concatenate spaces in order to shift the text over from the "symbols", and it uses rect to retroactively fit a box around the printed legend text.

    0 讨论(0)
  • 2020-12-31 04:49

    There are actually numerical equivalents for all symbols!

    Source: Dave Roberts

    The pch code is the concatenation of the Y and X coordinates of the above plot.

    • For example, the + symbol is in row (Y) 4 and column (X) 3, and therefore can be drawn using pch = 43.

    Example:

    plot(x=c(2,4,8),y=c(5,4,2),pch=16)
    points(x=c(3,5),y=c(2,4),pch="+")
    legend(7,4.5,pch=c(43,16),legend=c("A","B"))
    
    0 讨论(0)
  • 2020-12-31 04:59

    Use the numerical equivalent of the "+" character:

    plot(x=c(2,4,8),y=c(5,4,2),pch=16)
    points(x=c(3,5),y=c(2,4),pch="+")
    legend(7,4.5,pch=c(43,16),legend=c("A","B"))
    
    0 讨论(0)
  • 2020-12-31 05:00

    I bumped to this issue several time, so I wrote a tiny function below. You can use to specify the pch value, e.g.

    pch=c(15:17,s2n("|"))
    

    String to Numeric

    0 讨论(0)
  • 2020-12-31 05:10

    My first thought is to plot the legend twice, once to print the character symbols and once to print the numeric ones:

    plot(x=c(2,4,8),y=c(5,4,2),pch=16)
    points(x=c(3,5),y=c(2,4),pch="+")
    legend(7,4.5,pch=c(NA,16),legend=c("A","B")) # NA means don't plot pt. character 
    legend(7,4.5,pch=c("+",NA),legend=c("A","B"))
    

    NOTE: Oddly, this works in R's native graphical device (on Windows) and in pdf(), but not in bmp() or png() devices ...

    enter image description here

    0 讨论(0)
提交回复
热议问题