R: How to automate a variable creation procedure where I need to create a separate variable for each level of an existing variable

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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()
</code>
<code>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() </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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

New contributor

statsisfun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật