簡體   English   中英

包括一個類別變量和兩個數值變量的圖

[英]Plot including one categorical variable and two numeric variables

如何在圖表上顯示其對應類型的AverageTime和AverageCost值。 變量的規模不同,因為其中一個是時間的平均值,另一個是成本的平均值。 我想定義類型,因為x和y指的是AverageTime和AverageCost的值。 (在這種情況下,我將在一個圖形中有兩個折線圖)

Type<-c("a","b","c","d","e","f","g","h","i","j","k")
AverageTime<-c(12,14,66,123,14,33,44,55,55,6,66)
AverageCost<-c(100,10000,400,20000,500000,5000,700,800,400000,500,120000)
df<-data.frame(Type,AverageTime,AverageCost)

可以使用facet_wrapscales="free_y"來完成,如下所示:

library(tidyr)
library(dplyr)
library(ggplot2)

df %>%
  mutate(AverageCost=as.numeric(AverageCost), AverageTime=as.numeric(AverageTime)) %>%
  gather(variable, value, -Type) %>%
  ggplot(aes(x=Type, y=value, colour=variable, group=variable)) +
  geom_line() +
  facet_wrap(~variable, scales="free_y")

在此處輸入圖片說明

您可以在此處比較兩條線,即使它們的比例不同。

高溫超導

# install.packages("ggplot2", dependencies = TRUE)
library(ggplot2)
p <- ggplot(df, aes(AverageTime, AverageCost, colour=Type)) + geom_point()
p + geom_abline()

在此處輸入圖片說明

要在同一圖中顯示兩條線,將很難,因為它們的比例不同。 您還需要將AverageTime和AverageCost轉換為數字變量。

library(ggplot2)
library(reshape2)
library(plyr)

為了能夠在一條圖中繪制兩條線並取兩者的平均值,您需要進行一些重塑。

df_ag <- melt(df, id.vars=c("Type"))
df_ag_sb <- df_ag %>% group_by(Type, variable) %>% summarise(meanx = mean(as.numeric(value), na.rm=TRUE))

ggplot(df_ag_sb, aes(x=Type, y=as.numeric(meanx), color=variable, group=variable)) + geom_line()

在此處輸入圖片說明

暫無
暫無

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

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