[英]Line graph in ggplot2 with some categorical variables and shading
首先,我向你道歉,因为我一直在试图通过小部分切片它来解决这个问题(见1 , 2 , 3 )。 但是,将它们全部合并时,我完全陷于困境。 为了复制它并简化可重复性,您可以在此处下载原始数据 。
将它们加载到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_value
。 Y_value
。 如您在变量Units
看到的,我们有两个组( Uni1
和Uni2
),每个组由126个观测值组成。 更重要的是,每个单元中的这126个观测值由126个因素组成。 保持这些Y_values
的顺序非常重要,因此在折线图中, I1 if I2CP3P4M1M2
,则左上角的Y值应为I1 if I2CP3P4M1M2
,则左下角的Y值应为I1I2CP3 if P4M1M2
Uni1
和Uni2
。 Groups
表示的因子geom_rect()
可能使用geom_rect()
对背景进行geom_rect()
,但不表示矩形的轮廓并为6个组中的每一个保持不同的颜色。 希望这会有所帮助,虽然它并不完美,但可以使您更接近所需的内容:
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软件包 (v0.2.0)创建于2018-05-15。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.