简体   繁体   English

如何用ggplot上不同列的线连接两个点

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

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.此图显示了一个 geom_point 图,其中包含每年的最小值和最大值,但我不知道如何将这两个值与一条线连接起来,因为它们来自不同的列。 此图显示了一个 geom_point 图,其中包含每年的最小值和最大值,但我不知道如何将这两个值与一条线连接起来,因为它们来自不同的列。

Here is the code for the ggplot:这是ggplot的代码:

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

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:如果只需要将一列的数据连接到另一列的数据,可以使用geom_segment指定每个段的开头和结尾:

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")) 

在此处输入图片说明

The more typical way to work with ggplot2 is to convert your data into longer format, with each observation in its own row.使用 ggplot2 的更典型方法是将您的数据转换为更长的格式,每个观察都在自己的行中。 Longer data often has simpler plotting code with ggplot2, and it often takes care of legends more easily.较长的数据通常使用 ggplot2 具有更简单的绘图代码,并且通常更容易处理图例。 Reshaping the data can be done with dplyr and tidyr , two other of the packages included in library(tidyverse) .可以使用dplyrtidyr来重塑数据,这是library(tidyverse)包含的另外两个包。

library(dplyr); library(tidyr)

# data prep
tail(msleep) %>%
  select(name, awake, bodywt) %>%
  pivot_longer(-name, names_to = "stat", values_to = "val") %>%

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

在此处输入图片说明

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

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