ggplot中的组之间的连续线

ggplot中的组之间的连续线

本文介绍了ggplot中的组之间的连续线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据的时间序列,其中一些数据被观察,一些数据被模拟。我想生成一个随时间的整个数据系列的图,用颜色指示数据源。然而,我只能弄清楚如何在同一组中的ggplot连接点中使用geom_line()。

I've got a timeseries of data where some of the data is observed and some of the data is simulated. I would like to generate a plot of the entire data series over time, with the color indicating the data source. However, I can only figure out how to make geom_line() in ggplot connect points in the same group.

这里有一个例子来澄清:

Here's an example to clarify:

# Create sample data
df <- data.frame(cbind(seq(1,9,1), c(1,2,3,4,5,4,3,2,1), c("obs","obs", "obs", "obs", "sim","sim","obs","sim", "obs")))
colnames(df) <- c("time", "value", "source")

# Make a plot
p <- ggplot(df, aes(x=time, y=value, group=source, color=source))
p + geom_point()  # shows all the points in sequential order as dots
p + geom_point() + geom_line() # connects obs to obs and sim to sim

在这个例子中,从x轴的1:9开始顺序连接,连接所有点,但根据组更改线(和点)的颜色。

In this example, I would like a line to go sequentially from 1:9 on the x-axis, connecting all points, but change the color of the line (and points) based on the group.

推荐答案

df <- data.frame(cbind(
                       seq(1,9,1),
                       c(1,2,3,4,5,4,3,2,1),
                       c("obs","obs","obs","obs","sim","sim","obs","sim","obs"),
                       c("all","all","all","all","all","all","all","all","all")))

colnames(df) <- c("time", "value", "source", "group")

ggplot(df,aes(x=time,y=value)) +
    geom_point(aes(colour=source)) +
    geom_path(data=df,aes(y=value,x=time,group=group,colour=source))

这篇关于ggplot中的组之间的连续线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:15