逐行绘制两个固定行. [英] Plotting row by row together with two fixed rows.

查看:38
本文介绍了逐行绘制两个固定行.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想做一些折线图.让我们以 mtcars 为例.

As the title says I would like to do some line plots. Let's use the mtcars as an example.

我想从该数据集中绘制10行.我选择了那些:

I would like to plot in total 10 rows from this data set. I chose those ones:

> dput(vec)
c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710", "Hornet 4 Drive", 
"Hornet Sportabout", "Valiant", "Duster 360", "Merc 240D", "Merc 230", 
"Merc 280")

因此,我首先决定对整个数据集进行子集化:

So first of all I decided to subset the whole data set:

tbl_mtcars <- mtcars[row.names(mtcars) %in% vec, ]

,然后我想绘制这些行,但假设每个图上只有3条线.Merc 230和Merc 280的线应始终在图上,其余线应一一添加.

and than I would like to plot those rows but with the assumption that on each plot there will be only 3 lines. The lines for Merc 230 and Merc 280 should always be on the plot and the rest should be added one by one.

如果可以通过 ggplot 完成,那将是很棒的事情:

Would be great if that could be done with ggplot:

下面的函数只是我经常用于绘图的代码示例.

The function below is just the example of code which I often use for plotting.

ggplot(tbl_mtcars, aes(gear, carb, group=factor(Name))) +
  theme(legend.title=element_blank()) +
  geom_line(aes(color=factor(Name))) +
  ggtitle("Title")+
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

推荐答案

首先, mtcars 可能不是说明您需求的最佳数据集.相反,我创建了一个10行5列的数据框(代表观察结果).

First of all, mtcars might not be the best dataset to illustrate your need. Instead, I created a data frame of 10 rows and 5 columns (representing observations).

问题是, ggplot 需要特定形式的数据("long"而不是"wide"),因此在绘制图形之前,我们需要先修改数据.在这里,我使用 reshape2 包中的 melt .

The thing is, ggplot needs a specific form of data ('long' instead of 'wide'), so before we can draw a graph, we need to modify the data first. Here I use melt from reshape2 package.

现在,我们可以在记住您提到的两个固定行(ID)的同时生成图.在这里,最后两个ID是固定的.请注意,我在这里只展示香草型的地块,没有太多化妆品.

Now we can generate the plots while keeping in mind the two fix rows (IDs) you mentioned. Here, the last two IDs are fixed. Please note that I only present the vanilla-type of plots here, without much cosmetics.

(编辑/更新:按照@Paul Hiemstra的建议,将 for 循环替换为 lapply ,并删除 eval-parse 组合,尽管仍然保持 grid.arrange 方法)

(EDIT/UPDATE: as per @Paul Hiemstra's suggestion, replacing for loop with lapply and removing eval-parse combination, although still keeping the grid.arrange method)

# Generate data: 10 IDs each with 5 observations
df <- data.frame(matrix(rnorm(50), 10, 5))
df$id <- as.numeric(rownames(df))

# Melt the data
require(reshape2)
df2 <- melt(df, id.vars = "id")

# Generate plots
require(ggplot2)
plot.list <- lapply(1:(max(df2$id)-2), function(i) {
  df2.i <- df2[df2$id %in% c(i, 9, 10), ]
  ggplot(df2.i) +
    geom_line(aes(x = as.numeric(variable), y = value, colour = factor(id)))
})

# Combine plots
require(gridExtra)
do.call(grid.arrange, plot.list)

这篇关于逐行绘制两个固定行.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆