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

问题描述

'''

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")

输出:

enter image description here

如果您想研究密度,请尝试以下操作:

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

输出:

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...