を使用して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
Iを使用すると、以下のように、列の名前を目的の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ファミリーの一部としてますます使用されているので、私はきちんとしたアプローチを投稿すると思いました。
# 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行×1value
列col
でrowname
ありx
、この特定の場合は他のいくつかの識別子列(、および最終的に)が含まれます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加