I am trying to create a graph with different facets but each facets have the same lines and the only difference among the facets is that each facet highlights a different line (i.e., the only difference is the alpha values of the lines).
Python graph
I was able to create one in Python fairly easy:
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()
But I was having a hard time doing the same in R. I was able to do it in R eventually but in a dummy way — it will get very cumbersome if the base variable has many levels.
In R i did this:
R graph
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)
And then in ggplot2, for the alpha values in geom_line, i just used alpha_value
and then facet_wrap
by 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)
As you can see, i had to create dummy variables (X_Line) for each facet– This can get quite hard if the highlight_var
has many levels.
Is there any way to create an iterative function to automate the “_Line” variables creation process? Thanks so much!
I tried to write functions using “for” loops but to no avail. I was thinking using grid.arrange
to group the outputs but couldn’t seem to store the graphs from the loop into an object that can be put in grid.arrange
statsisfun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.