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

问题描述 投票:0回答:1

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

Fake data

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)

Attempt

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

Desired result

enter image description here

r ggplot2 plot
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.