简体   繁体   中英

Overlay two plots (ggplot)

How I can overlay the scatter plot of AverageTime2 vs. AverageCost and AverageTime1 vs. AverageCost. (in ggplot)?

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)
AverageTime2<-c(14,15,66,126,14,100,144,55,55,16,90)
AverageCost<-c(100,10000,400,20000,500000,5000,700,800,400000,500,120000)
AverageCost2<-c(10000,10000,4000,20000,5000,50000,7000,8000,40000,50000,120000)
df<-data.frame(Type,AverageTime,AverageTime2,AverageCost,AverageCost2)

You can simply build your data like this

df<-rbind(data.frame(Type,AverageTime,AT="T1",AverageCost,AverageCost2),
          data.frame(Type,AverageTime=AverageTime2,AT="T2",
                     AverageCost,AverageCost2))

and plot it that way

library(ggplot2)
ggplot(df)+geom_point(aes(AverageTime, AverageCost,color=AT))

在此处输入图片说明

You'll need to reshape your data so that the AverageTime and AverageCost are each a column, with a separate column (called something like Type2 ) that distinguishes the two types.

You can accomplish this with dplyr, tidyr, and stringr:

library(dplyr)
library(tidyr)
library(stringr)

df_gather <- df %>%
  gather(column, value, -Type) %>%
  mutate(Type2 = str_detect(column, "2"),
         column = str_replace(column, "2", "")) %>%
  spread(column, value)

The particularly important part of that is to gather all the "Average" columns into one column, then to distinguish them (using the Type2 column), and then to spread them back into separate AverageCost and AverageTime columns.

Afterwards, you can simply do:

ggplot(df_gather, aes(AverageTime, AverageCost, color = Type2)) +
  geom_point()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM