首页 > 解决方案 > 如何使用数据表的两列在ggplot2中定义x轴上的范围

问题描述

我有以下数据表

    name        rating  min_date    max_date    weight
1   abc123      39     2018-04-29   2018-04-29  2000
2   abc123      80     2018-04-16   2018-07-31  3131

使用它,我想使用 ggplot 库为每一行绘制一条线,在 x 轴上保持最小日期到最大日期,在 y 轴上进行评级,并且线的颜色会根据重量而变化。

标签: rggplot2

解决方案


我更改了数据,因为第一行中的数据相同min_date,并且max_date只有两个观察结果。

data <- read.table(text = "name        rating  min_date    max_date    weight
1   abc123      39     2018-04-29   2018-06-29  2000
2   abc123      80     2018-04-16   2018-07-31  3131
3   abc123      56     2018-04-15   2018-05-30  1831", header = T)

一种选择是weight在绘图中作为连续变量:

library(ggplot2)

ggplot(data, aes(x = min_date, xend = max_date, 
                 y = rating, yend = rating, 
                 col = weight)) + 
  geom_segment()

在此处输入图像描述

第二种选择是将 is 作为一个因素:

ggplot(data, aes(x = min_date, xend = max_date, 
                 y = rating, yend = rating, 
                 col = as.factor(weight))) + 
  geom_segment()

在此处输入图像描述


推荐阅读