簡體   English   中英

如何在 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()

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM