根据数据变量绘制颜色和形状的点

时间:2022-05-03 12:17:34

I am trying to make a scatter plot with the colors of each point corresponding to one variable and the shape of each point corresponding to another variable. Here is some example data and the code I used to make the second plot:

我试图制作一个散点图,每个点的颜色对应一个变量,每个点的形状对应另一个变量。这是一些示例数据和我用于制作第二个图的代码:

Example data:(of 3 points)
 X    Y    att1    att2

.5    .5    1       A
.24   .8    3       B
.6    .7    5       C

code:(for image2)
> plot(X,Y, col=statc[att2], pch = 15)
> legend("right", statv, fill=statc)

Where:
> statv
[1] "A"  "B" "C"  
> statc
[1] "red"    "blue"   "orange"

I have done this individually but dont know how to do both. Here is two plots:

我已经单独完成了这项工作但不知道如何做到这两点。这是两个图:

1根据数据变量绘制颜色和形状的点

2根据数据变量绘制颜色和形状的点

For example: I want the colors to apply to the points with the same att1 and the shapes to apply to points with the same att2

例如:我希望颜色应用于具有相同att1的点和要应用于具有相同att2的点的形状

2 个解决方案

#1


20  

One of the domain where ggplot2 excels , comparing to other R system plots, is mapping plot parameters to data variables.( via aesthetics mechanism)

与其他R系统图相比,ggplot2擅长的领域之一是将绘图参数映射到数据变量。(通过美学机制)

library(ggplot2)
dat <- data.frame(X =runif(20),
                     Y =runif(20),
                     att1 = gl(5,20/5),
                     att2 =gl(3,20/3))
ggplot(dat,aes(x=X,y=Y,color=att1,shape=att2)) +
    geom_point(size=5) 

根据数据变量绘制颜色和形状的点

You can do it in the base plot also, but you should generate manually the legend ...

您也可以在基础图中执行此操作,但您应手动生成图例...

plot(dat$X,dat$Y,pch=as.integer(dat$att1),col=as.integer(dat$att1))

根据数据变量绘制颜色和形状的点

#2


3  

Is this what you want? [df is your data formatted as above.]

这是你想要的吗? [df是您的数据格式如上。]

library(ggplot2)
ggplot(df) + geom_point(aes(x=X,y=Y,color=factor(att1),shape=att2),size=5)

Produces this with your data:

使用您的数据生成:

根据数据变量绘制颜色和形状的点

#1


20  

One of the domain where ggplot2 excels , comparing to other R system plots, is mapping plot parameters to data variables.( via aesthetics mechanism)

与其他R系统图相比,ggplot2擅长的领域之一是将绘图参数映射到数据变量。(通过美学机制)

library(ggplot2)
dat <- data.frame(X =runif(20),
                     Y =runif(20),
                     att1 = gl(5,20/5),
                     att2 =gl(3,20/3))
ggplot(dat,aes(x=X,y=Y,color=att1,shape=att2)) +
    geom_point(size=5) 

根据数据变量绘制颜色和形状的点

You can do it in the base plot also, but you should generate manually the legend ...

您也可以在基础图中执行此操作,但您应手动生成图例...

plot(dat$X,dat$Y,pch=as.integer(dat$att1),col=as.integer(dat$att1))

根据数据变量绘制颜色和形状的点

#2


3  

Is this what you want? [df is your data formatted as above.]

这是你想要的吗? [df是您的数据格式如上。]

library(ggplot2)
ggplot(df) + geom_point(aes(x=X,y=Y,color=factor(att1),shape=att2),size=5)

Produces this with your data:

使用您的数据生成:

根据数据变量绘制颜色和形状的点