How do I transform a data frame and make multiple line graphs in R?

余生长醉 提交于 2021-02-08 10:30:12

问题


I have a data frame as below

    0-10  10-20  20-30  30-40
 M  1     2.5     4     0.3

 N 0.5   0.8     2.3     1

The 0-10, 10-20 intervals is my first row without any column headings. I want to plot two line graphs on the same graph depicting M and N values on y-axis and the intervals 0-10, 10-20 etc. as my X-axis. How do I go about doing that? If I make the intervals as my heading, then I am unable to plot these graphs using ggplot as I do not have a x variable for aes()


回答1:


A bit hard without the data, but I've created something that looks like what you describe, minus the first row, which contains your labels for the x-axis:

df <- structure(list(V1 = c(1, 0.5), V2 = c(2.5, 0.8), V3 = c(4, 2.3
), V4 = c(0.3, 1)), class = "data.frame", row.names = c("M", 
"N"))

df
       V1  V2  V3  V4
    M 1.0 2.5 4.0 0.3
    N 0.5 0.8 2.3 1.0

Usually, you want a data frame in the other orientation, here we can use the t function (transform):

library(tidyverse)

as_tibble(t(df))
# A tibble: 4 x 2
      M     N
  <dbl> <dbl>
1   1     0.5
2   2.5   0.8
3   4     2.3
4   0.3   1

Then you can reshape it into a format suitable for ggplot.

as_tibble(t(df)) %>%
  mutate(x=row_number()) %>%
  pivot_longer(-x) %>%
  ggplot(aes(x=factor(x), y=value, group=name, col=name)) +
  geom_line() +
  scale_x_discrete(labels=c("0-10", "10-20", "20-30", "30-40"))

Or you can use the first row of your original data frame for the labels.




回答2:


Some fundamental issues - you need a specific x value and not a range (0-10, etc;). It is best to provide an easily reproducible example. However, based on details you have posted, and making an assumption that you want the y's plotted against the mid-points of the ranges provided for x - you could something like this quite easily:

x<-   c("0-10",  "10-20",  "20-30",  "30-40")
xm <- c(5,15,25,35)
M <-  c(1, 2.5, 4, 0.3)
N <- c(0.5, 0.8, 2.3, 1)

df <- as.data.frame(rbind(xm,M,N))
names(df) <- x
df
matplot(xm, cbind(M, N), t="l", lty=1, col=c("red", "blue"), xaxt = "n", xlab='2 Lines', ylab = c("M = red", "N = blue"))
axis(1, at=xm, labels=x)
# plot:
# I see that a nice ggplot solution has just been posted & so will leave you with this...





来源:https://stackoverflow.com/questions/60909937/how-do-i-transform-a-data-frame-and-make-multiple-line-graphs-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!