简体   繁体   中英

How to manually change linetypes in ggplot2

I'd like to manually change linetypes for a few lines in an interaction plot in ggplot. Essentially, x = continuous y = continuous, moderator = categorical (5 levels).

I have specified the desired linetypes using the scale_linetype_manual argument, but for whatever reason, the linetypes are not changing. I am able to successfully change the line colors but not the linetypes.

ggplot(data=subset(study6, !is.na(condition_control)), aes(x=attitude, y=support, color=condition_control)) + 
  stat_smooth(method="lm", se = FALSE) + 
  labs(x ="Initial attitudes", y = "Policy support") +
  guides(color=guide_legend(title="Condition")) +
  scale_linetype_manual(values=c("solid", "dashed", "solid", "dashed", "solid")) + 
  scale_color_manual(values=c("red", "gray70", "gray70", "black", "black")) +
  theme_bw()

Perhaps the issue has to do with the categorical moderating variable (condition_control)? Any suggestions you have on the matter would be appreciated.

For others who may have this issue, I figured it out!

You have to specify your moderator as both a color and a linetype in the aes function. (Note: This will give you two different legends, so you have to make sure each legend is given the same title in order to collapse them into a single legend.)

ggplot(data=subset(study6, !is.na(condition_control)), aes(x=attitude, y=support, color=condition_control, linetype = condition_control)) + 
  stat_smooth(method="lm", se = FALSE) + 
  labs(x ="Initial attitudes", y = "Policy support") +
  guides(color=guide_legend(title="Condition")) +
  scale_linetype_manual("Condition", values=c("solid", "twodash", "solid", "twodash", "solid")) +
  scale_color_manual("Condition", values=c("red", "gray70", "gray70", "black", "black")) +
  theme_bw()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM