从包含列表作为列值的数据框中绘制
plot from a dataframe containing lists as column values
我一直在使用 purrr 包,现在遇到了一个独特的问题。我想绘制数据框,其中值是包含列内值的列表。
结构:
a b x y
1 1 c(1,2,3,4) c(4,5,6,7)
1 2 c(1,2,3,4) c(5.4,6,6.5,7)
尝试的解决方案:
library("tidyverse")
# Define a named list of parameter values
temp = list(a = seq(1,5,1),
b = seq(0.1,3,1)) %>% cross_df()
# create two new columns
x <- seq(1,5,0.1)
y <- 2.3 * x
# add these as a list
temp$x <- list(x)
temp$y <- list(y)
ggplot(data=temp, aes(x=unlist(x),y=unlist(y),color=a)) +
geom_point() +
ggtitle("Plot of Y vs. X shown by colour of a")
错误:
- 错误:美学必须是长度 1 或与数据相同 (15):x、y、颜色 使用 unlist
- 错误:在不使用 unlist
时向连续刻度提供离散值
您需要将列表元素分成单独的行,这可以使用 unnest
来完成
library(tidyverse)
temp %>%
unnest() %>%
ggplot() +
aes(x,y,color=a) +
geom_point() +
ggtitle("Plot of Y vs. X shown by colour of a")
我一直在使用 purrr 包,现在遇到了一个独特的问题。我想绘制数据框,其中值是包含列内值的列表。
结构:
a b x y
1 1 c(1,2,3,4) c(4,5,6,7)
1 2 c(1,2,3,4) c(5.4,6,6.5,7)
尝试的解决方案:
library("tidyverse")
# Define a named list of parameter values
temp = list(a = seq(1,5,1),
b = seq(0.1,3,1)) %>% cross_df()
# create two new columns
x <- seq(1,5,0.1)
y <- 2.3 * x
# add these as a list
temp$x <- list(x)
temp$y <- list(y)
ggplot(data=temp, aes(x=unlist(x),y=unlist(y),color=a)) +
geom_point() +
ggtitle("Plot of Y vs. X shown by colour of a")
错误:
- 错误:美学必须是长度 1 或与数据相同 (15):x、y、颜色 使用 unlist
- 错误:在不使用 unlist 时向连续刻度提供离散值
您需要将列表元素分成单独的行,这可以使用 unnest
library(tidyverse)
temp %>%
unnest() %>%
ggplot() +
aes(x,y,color=a) +
geom_point() +
ggtitle("Plot of Y vs. X shown by colour of a")