简体   繁体   English

仅从R矩阵中的某些行绘制点

[英]Plotting points from only certain rows in a matrix in R

I am new to R so it's probably very basic, but I am trying to add colored points for certain values to a plot of a matrix "m". 我是R的新手,所以它可能非常基础,但是我试图将某些值的有色点添加到矩阵“ m”的图中。 I need to add points from the same matrix, but only for the rows containing values within the range 169 to 179. What code can I use for this? 我需要添加来自同一矩阵的点,但只需要为包含值在169到179范围内的行添加点。我可以为此使用什么代码? I tried: 我试过了:

p <- which(m[,2]==169:179
## and
points (p, col="blue")

and it doesn't work. 而且不起作用。 How can I write these codes properly to put these coordinates in blue on the graph? 如何正确编写这些代码,以将这些坐标在图表上显示为蓝色? thanks! 谢谢!

You can try to define a function that test if a number is in between your two values: 您可以尝试定义一个测试两个值之间是否存在数字的函数:

inbetween = function(x)
{
     return ( x >= 169 & x <= 179 )
}

And then call it on each value of m[,2] with the function sapply: ind = sapply( m[,2], inbetween ) Which gives you a vector of True or False according if the given value if in the range or not. 然后使用函数sapply在m [,2]的每个值上调用它: ind = sapply( m[,2], inbetween )根据给定值是否在范围内ind = sapply( m[,2], inbetween )它会为您提供True或False向量。 Then taking p = m[ind,] will give you the rows of m at those selected indices. 然后取p = m[ind,]将为您提供这些选定索引处的m行。

It would be good if you could share an example of your data. 如果您可以共享一个数据示例,那就太好了。 In general it makes more sense to plot data from a data frame, opposed to a matrix. 通常,从矩阵而不是矩阵中绘制数据更为有意义。 We can use the pre-installed mtcars dataset to demonstrate your solution. 我们可以使用预先安装的mtcars数据集来演示您的解决方案。

Let's first have a look at the data available in the dataset: 首先让我们看一下数据集中的可用数据:

summary(mtcars)

Next, we can filter the data that we want to display. 接下来,我们可以过滤要显示的数据。 In this case we are filtering mtcars$mpg (the column with the name mpg ) for values between 15 and 20. To make it easier, we assign this filtered data frame as a new data frame. 在这种情况下,我们正在筛选mtcars$mpg (名称列mpg 15和20之间的值为了方便,我们分配该过滤后的数据帧作为新的数据帧)。

mtcars_filtered <- mtcars[mtcars$mpg >= 15 & mtcars$mpg <= 20 , ]

Lastly, we can plot the data. 最后,我们可以绘制数据。 In this case, we want the mpg column to be the x values and hp to be the y values. 在这种情况下,我们希望mpg列是x值,而hp是y值。 type is used to specify how we want to display it ( "p" for points), and col is used to specify the color ( "blue" for blue). type用于指定显示方式(点为"p" ), col用于指定颜色( "blue""blue" )。

plot(mtcars_filtered$mpg, mtcars_filtered$hp, type = 'p', col = 'blue')

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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