【问题标题】:Line graph in ggplot2 with some categorical variables and shadingggplot2中带有一些分类变量和阴影的折线图
【发布时间】:2018-05-15 08:30:43
【问题描述】:

首先,我很抱歉,因为我一直试图通过将其分成小部分来解决此问题(请参阅123)。但是,在合并所有这些时我完全被卡住了。为了复制它并简化重现性,您可以download the original data here

在 R 中加载它们后,结构如下:

> str(data_example2)
'data.frame':   252 obs. of  4 variables:
 $ Groups  : Factor w/ 6 levels "Group1","Group2",..: 1 1 1 1 1 1 1 2 2 2 ...
 $ Y_values: Factor w/ 126 levels "C if I1I2P3P4M1M2",..: 63 95 1 115 123 112 114 48 17 67 ...
 $ Units   : Factor w/ 2 levels "Uni1","Uni2": 1 1 1 1 1 1 1 1 1 1 ...
 $ X_value : num  1 0.35 0.93 0.73 0.95 0.32 0.88 0.13 0.93 0.84 ...

那么,我想要什么?我想使用这些条件在 ggplot2 中构建折线图:

  • X轴代表变量X_value
  • Y 轴代表变量Y_value。正如您在变量Units 中看到的,我们有两组(Uni1Uni2),每组由 126 个观察值组成。更重要的是,每个单元中的这 126 个观测值是由 126 个因子组成的。 保持这些Y_values 的顺序 非常重要,因此折线图中左上角的 Y 值应为I1 if I2CP3P4M1M2,左下角应为I1I2CP3 if P4M1M2
  • 我想追踪两行,Uni1,另一行Uni2
  • 我想使用变量Groups 中表示的因子对背景进行着色,可能使用geom_rect(),但不表示矩形的轮廓并为6 组中的每组保持不同的颜色。

最终图表应该是这样的,但每个 Groups 都有阴影。

【问题讨论】:

  • 您可能在这里犯了一些错误。你说 2 组 Uni1Uni2 但你的 str() 显示你有 6 个级别,而不是 2。你说 126 个观察,但你的 str() 显示 125 个级别,而不是 126。
  • 哦。 Units 由 2 个组组成,变量 Groups 由 6 个组成。我要检查 Y_vales。谢谢
  • 我更新了数据集,在 Y_values 列中有 126 个因子。

标签: r ggplot2


【解决方案1】:

希望这会有所帮助,它并不完美,但可以让您更接近您的需求:

library(readr)
library(ggplot2)

y_val_levels <- unique(df$Y_values)

使用geom_ribbon

ggplot(df, aes(x = factor(Y_values, levels = y_val_levels, ordered = TRUE))) +
  geom_ribbon(aes(ymin = -Inf, ymax = Inf, fill = Groups, group = Groups), alpha = .2) +
  geom_line(aes(y = X_value, color = Units, group = Units)) +
  geom_point(aes(y = X_value, color = Units)) +
  scale_x_discrete('Bayesian combination') +
  coord_flip() +
  theme_minimal() +
  theme(axis.text.y = element_text(size = 5))

使用geom_rect

ggplot(df, aes(x = factor(Y_values, levels = y_val_levels, ordered = TRUE))) +
  geom_rect(aes(xmin = as.integer(factor(Y_values, levels = y_val_levels, ordered = TRUE)) - .5,
                xmax = as.integer(factor(Y_values, levels = y_val_levels, ordered = TRUE)) + .5,
                ymin = -Inf, 
                ymax = Inf, 
                fill = Groups, group = Groups), alpha = .2) +
  geom_line(aes(y = X_value, color = Units, group = Units)) +
  geom_point(aes(y = X_value, color = Units)) +
  scale_x_discrete('Bayesian combination') +
  coord_flip() +
  theme_minimal() +
  theme(axis.text.y = element_text(size = 5))

(请注意,较暗的切片是由于Y_values中的重复值)

reprex package (v0.2.0) 于 2018 年 5 月 15 日创建。

【讨论】:

  • 哇!我更喜欢功能区选项而不是矩形。最后一件事,如何反转 Y 轴?
  • 知道如何颠倒 Y 轴吗?
  • 一个想法可能是aes(x = forcats::fct_rev(factor(Y_values, levels = y_val_levels, ordered = TRUE))),我相信有更简单的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多