【问题标题】:how to define a range on x axis in ggplot2 using two columns of a data table如何使用数据表的两列在ggplot2中定义x轴上的范围
【发布时间】:2018-08-28 14:09:46
【问题描述】:

我有以下数据表

    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 轴上进行评级,线条的颜色会根据重量而有所不同。

【问题讨论】:

  • 我试图弄清楚这张图会是什么样子......似乎只有一个 y 值,所以我不确定如何与它划线。你能澄清或展示一个手绘的例子吗?从那里应该很容易得到答案。

标签: r ggplot2


【解决方案1】:

我更改了数据,因为第一行有相同的 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()

第二个选项是考虑因素:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    相关资源
    最近更新 更多