简体   繁体   English

如何使用ggplot自动绘制多个数据集?

[英]How to plot multiple data sets using ggplot automatically?

I have a data file that looks like this: 我有一个数据文件,看起来像这样:

X1_axis Y1_axis X2_axis Y2_axis X1_axis Y1_axis X2_axis Y2_axis X1_axis Y1_axis X2_axis Y2_axis

values values values values values values values values

X1_axis is the coordinate of axis number one and Y1_axis are the data number one to be represented on the y_axis and so on. X1_axis是第一个轴的坐标,Y1_axis是要在y_axis上表示的数据第一个,依此类推。

One solution is: 一种解决方案是:

require(ggplot2)
p + geom_line(aes(x = X1_axis, y = Y1_axis, col = "plot 1")) + 
geom_line(aes(x = X2_axis, y = Y2_axis, col = "plot 2"))

Is there a shorter and better way to do this? 有没有更短更好的方法? If I have 20 of such pairs plotting them using this method takes a lot of typing and the codes looks ugly. 如果我有20对这样的对,使用这种方法绘制它们会花费很多时间,并且代码看起来很难看。

This should do the job using dplyr to create some new variables (mutate), tidyr to transpose the data (gather and spread) and stringr to grab the number out of the axis name (str_extract). 这应该使用dplyr来创建一些新变量(mutate),tidyr来进行数据转置(收集并散布),stringer来从轴名称(str_extract)中获取数字来完成此工作。

library(dplyr)
library(tidyr)
library(stringr)
library(ggplot2)

df <- data.frame(x1_axis = runif(5),
             y1_axis = runif(5),
             x2_axis = runif(5),
             y2_axis = runif(5)
)

df_transpose <- df %>%
  mutate(observation_number = row_number()) %>%  #Add an observation number column
  gather(axis, value, -observation_number) %>%  #flatten the data
  mutate(group_var = str_extract(axis, "[0-9]+")) %>%  #grab numeric part of the axis name to use as a grouping variable
  mutate(axis = gsub('[0-9]+', '', axis)) %>%  #remove numbers from the axis names
  spread(axis, value) %>% #pivot the axis names back to columns again
  arrange(group_var, observation_number)  #tidy up

ggplot(data = df_transpose, aes(x = x_axis, y = y_axis, group = group_var)) +
       geom_line()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM