如何在 R 中表示两个定量变量并根据分类变量为图着色?

How can I represent in R two quantitative variables and color the plot according to a categorical variable?

'''

my_data<-iris

''' '''

length.ratio<- my_data$Sepal.Length/my_data$Petal.Length
width_ratio<-my_data$Sepal.Width/my_data$Petal.Width

''' '''

my_data$Species<-as.factor(my_data$Species)

''' #尝试使用ggplot2绘图

'''

ggplot(my_data,aes(length_ratio,fill=Species))+theme_bw()+
  facet_wrap(width.ratio~Species)+ geom_density(alpha=0.5)+
  labs(x="Width Ratio", y="Length Ratio")

'''

#其实我也不知道哪个'geom_plot'是最好的选择

您似乎在寻找散点图。所以试试这个,并始终尝试将变量保留在数据框中。如果将变量存储在同一个数据框中,则不必创建新因子。这里的代码:

library(ggplot2)
#Data
my_data<-iris
#Compute variables
my_data$length.ratio<- my_data$Sepal.Length/my_data$Petal.Length
my_data$width_ratio<-my_data$Sepal.Width/my_data$Petal.Width

剧情:

#Plot
ggplot(my_data,aes(width_ratio,length.ratio,color=Species))+
  geom_point(alpha=0.5)+
  theme_bw()+
  facet_wrap(~Species,scales='free')+
  labs(x="Width Ratio", y="Length Ratio")

输出:

如果你想研究密度,试试这个:

#Plot 2
ggplot(my_data,aes(length.ratio,color=Species,fill=Species))+
  geom_density(alpha=0.5)+
  theme_bw()

输出: