在x-y轴上绘制一个变量的子集(避免扩展/重塑数据帧)

时间:2018-09-08 10:09:37

标签: r ggplot2 plot

我想知道是否有可能在其中绘制一个变量的行子集 x-y轴而不必扩展/重塑数据框?

假数据

library(tidyverse)
id <- 1:6
size <- c(5, 2, 3, 4, 2, 8)
colour <- rep(c("red", "blue", "green"), 2)
df <- data.frame(id, size, colour)

尝试

x11()
ggplot(data = filter(df, colour %in% c("blue", "red")),
       aes(x = size[colour == "blue"],
           y = size[colour == "red"])) +
  geom_point()

所需结果

enter image description here

1 个答案:

答案 0 :(得分:1)

是的,有可能。一种解决方案是直接向aes提交向量(IMO这是对ggplot2的滥用,但是现在我想不出任何其他解决方案了。)

# Subset data once so we wouldn't need to subset twice for nrow 
id <- 1:6
size <- c(5, 2, 3, 4, 2, 8)
colour <- rep(c("red", "blue", "green"), 2)
df <- data.frame(id, size, colour)
pd <- subset(df, colour %in% c("blue", "red"))

# Use dummy empty data.frame
library(ggplot2)
ggplot(data.frame(), 
       # Submit x,y values as vectors that go every second entry
       aes(pd$size[seq(2, nrow(pd), 2)], pd$size[seq(1, nrow(pd), 2)])) +
    geom_point()

enter image description here

相关问题