使用 matplot
,我可以在给定的 x 值处为数据帧的每一行绘制一条线。例如
set.seed(1)
df <- matrix(runif(20, 0, 1), nrow = 5)
matplot(t(df), type = "l", x = c(1, 3, 7, 9)) # c(1, 3, 7, 9) are the x-axis positions I'd like to plot along
# the line colours are not important
我想使用 ggplot2 来代替,但我不确定如何最好地复制结果。使用 melt
我可以将列重命名为所需的 x 值,如下所示。但是我缺少一种“更干净”的方法吗?
df1 <- as.data.frame(df)
names(df1) <- c(1, 3, 7, 9) # rename columns to the desired x-axis values
df1$id <- 1:nrow(df1)
df1_melt <- melt(df1, id.var = "id")
df1_melt$variable <- as.numeric(as.character(df1_melt$variable)) # convert x-axis values from factor to numeric
ggplot(df1_melt, aes(x = variable, y = value)) + geom_line(aes(group = id))
任何帮助将不胜感激。谢谢
最佳答案
由于 ggplot2 越来越多地用作 tidyverse 的一部分系列软件包,我想我应该发布一个 tidy方法。
# generate data
set.seed(1)
df <- matrix(runif(20, 0, 1), nrow = 5) %>% as.data.frame
# put x-values into a data.frame
x_df <- data.frame(col=c('V1', 'V2', 'V3', 'V4'),
x=c(1, 3, 7, 9))
# make a tidy version of the data and graph
df %>%
rownames_to_column %>%
gather(col, value, -rowname) %>%
left_join(x_df, by='col') %>%
ggplot(aes(x=x, y=value, color=rowname)) +
geom_line()
关键思想是gather()
将数据转换为整齐的格式,以便数据不再是 5 行 × 4 列,而是 20 行 × 1 value
列以及其他一些标识符列(在本例中为 col
、 rowname
以及最终 x
)。
关于r - 使用 ggplot2 在给定的 x 值处绘制数据帧的每行一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121184/