# 如何使用ggplot在不同列上连接两个点的线。

go评论79阅读模式

How to connect two points with a line from different columns on ggplot

# 问题

``````# 绘制年份（y）和最大值与最小值的点（x）
ggplot(phen2, aes(y=Year)) +
geom_point(aes(x = max, color = "max")) +
geom_point(aes(x = min, color = "min"))
``````

I have a dataset that has a three columns: a year, a minimum value, and a maximum value. I want to plot a line between the min and max value for each year.

This plot shows a geom_point plot with the min and max values from each year but I do not know how to connect the two values with a line since they come from different columns.

Here is the code for the ggplot:

``````#plot year (y) and max and min points (x)
ggplot(phen2, aes(y=Year)) +
geom_point(aes(x = max, color = &quot;max&quot;)) +
geom_point(aes(x = min, color = &quot;min&quot;))
``````

# 答案1

``````library(ggplot2)
ggplot(tail(msleep), aes(y = name)) +
geom_segment(aes(x = awake, xend = bodywt, yend = name)) +
geom_point(aes(x = awake, color = "awake")) +
geom_point(aes(x = bodywt, color = "bodywt"))
``````

``````library(dplyr)
library(tidyr)

# 数据准备
tail(msleep) %>%
select(name, awake, bodywt) %>%
pivot_longer(-name, names_to = "stat", values_to = "val") %>%

# 稍微简化的绘图并将颜色映射到源列
ggplot(aes(x = val, y = name)) +
geom_line() +
geom_point(aes(color = stat))
``````

If you just need to connect the data from one column to the data from another column, you can use `geom_segment` to specify the beginning and end of each segment:

``````library(ggplot2)
ggplot(tail(msleep), aes(y = name)) +
geom_segment(aes(x = awake, xend = bodywt, yend = name)) +
geom_point(aes(x = awake, color = &quot;awake&quot;)) +
geom_point(aes(x = bodywt, color = &quot;bodywt&quot;))
``````

The more typical way to work with ggplot2 is to convert your data into longer format, with each observation in its own row. Longer data often has simpler plotting code with ggplot2, and it often takes care of legends more easily. Reshaping the data can be done with `dplyr` and `tidyr`, two other of the packages included in `library(tidyverse)`.

``````library(dplyr); library(tidyr)

# data prep
tail(msleep) %&gt;%
select(name, awake, bodywt) %&gt;%
pivot_longer(-name, names_to = &quot;stat&quot;, values_to = &quot;val&quot;) %&gt;%

# slightly simpler plotting &amp; mapping color to source column
ggplot(aes(x = val, y = name)) +
geom_line() +
geom_point(aes(color = stat))
``````

• 本文由 发表于 2020年1月4日 01:40:16
• 转载请务必保留本文链接：https://go.coder-hub.com/59582983.html
• ggplot2
• r

go 43

go 43

go 70

go 40