我正在尝试创建一个具有不同面的图形,其中每个面都有相同的线,面之间的唯一区别是每个面突出显示不同的线(即,唯一的区别是线的 alpha 值)。
我能够相当轻松地用 Python 创建一个:
time = np.array([1, 2, 3, 4, 5])
lines = np.array([
[10, 15, 20, 25, 22],
[8, 12, 18, 22, 17],
[5, 10, 15, 20, 16],
[12, 15, 17, 25, 30]
])
alpha_values = [1, 1, 1, 1] # Different alpha values for each line
colors = sns.color_palette("coolwarm", len(lines))
markers = ['o', 'd', 'D', 's']
line_styles = ['-', '--', '-.', ':']
# Create subplots
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(16, 8))
axs = axs.flatten()
# Plot each line with different alpha in each subplot
for i, ax in enumerate(axs):
for j, line in enumerate(lines):
alpha = alpha_values[j] if i == j else 0.2 # Highlight the line in the current subplot
color=colors[j] #if i==j else "gray"
marker=markers[j]
linestyle=line_styles[j]
ax.plot(time, line, label=f'Line {chr(ord("A") + j)}', alpha=alpha, marker=marker, color=color, linestyle=linestyle)
ax.set_title(f'Subplot {i + 1}')
ax.legend(ncol=1)
plt.figure(dpi=1500)
plt.tight_layout()
但我在 R 中做同样的事情很难。我最终能够在 R 中做到这一点,但以一种虚拟的方式——如果基本变量有很多级别,它会变得非常麻烦。
在 R 中我这样做了:
df <- data.frame(
x = rep(1:10, 4),
y = c(rnorm(10), rnorm(10, mean = 2), rnorm(10, mean = 4), rnorm(10, mean = 6)),
highlight_var = rep(c("A", "B", "C", "D"), each = 10)
)
df = df %>%
mutate(A_Line = ifelse(highlight_var=="A", 1,0.2),
B_Line = ifelse(highlight_var=="B", 1,0.2),
C_Line = ifelse(highlight_var=="C", 1,0.2),
D_Line = ifelse(highlight_var=="D", 1,0.2)) %>%
group_by(x, highlight_var) %>%
gather(alpha_group, alpha_value, A_Line:D_Line)
然后在ggplot2中,对于
geom_line
中的alpha值,我只是使用alpha_value
,然后使用facet_wrap
的
alpha_group
ggplot(df) +
geom_line(aes(x = x, y = y, color=highlight_var, alpha=alpha_value)
) +
scale_color_manual(values=c("red", "purple", "orange", "steelblue4"))+
facet_wrap(.~alpha_group)+
theme_minimal()+
guides(alpha=F)
如您所见,我必须为每个方面创建虚拟变量(X_Line)——如果
highlight_var
有很多级别,这可能会变得相当困难。
有什么方法可以创建迭代函数来自动执行“_Line”变量创建过程?非常感谢!
我尝试使用“for”循环编写函数,但没有成功。我正在考虑使用
grid.arrange
对输出进行分组,但似乎无法将循环中的图形存储到可以放入 grid.arrange
中的对象中
这个功能应该可以工作:
library(gridExtra)
library(ggplot2)
plot_list <- lapply(unique(df$highlight_var), function(highlight) {
ggplot(df, aes(x = x, y = y, group = highlight_var, color = highlight_var)) +
geom_line(aes(alpha = ifelse(highlight_var == highlight, 1, 0.2)), linewidth = 1) +
scale_color_manual(values = c("firebrick3", "purple3", "gold3", "steelblue3")) +
labs(title = paste("Highlight Group:", highlight)) +
theme_minimal() +
guides(alpha = FALSE)
})