首页 > 解决方案 > 在 R 中的一张图上绘制多条线

问题描述

数据

我试图绘制上面的数据集,其中会话是 x 轴,y 轴是平均值,并且在几周内每个方程都有不同,这在图例中表示。我无法生成图表并尝试了一些不同的选项:

ggplot(meant41, aes(x=Group.2, y=Q1, group=1)) + 
geom_line(aes(y=Q2)) +
geom_line(aes(y=Q3)) +
geom_line(aes(y=Q4)) +
geom_line(aes(y=Q5)) +
geom_line(aes(y=Q6)) +
geom_line(aes(y=Q7)) +
geom_line(aes(y=Q8)) +
geom_line(aes(y=Q9)) +
geom_line(aes(y=Q10)) +
geom_line(aes(y=Q11)) +
geom_point(size=3, shape=21, fill="black") 
xlab("Session") +
ylab("Mean") +
scale_colour_hue(name="Adherence Criteria",    # Legend label, use darker colors
               breaks=c("Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10", "Q11"),
               labels=c("Hierarchy", "Dialectics", "Dialectical Modeling", "Reciprocal Communicaton",
                        "Irreverent", "V2", "V5", "Behavioral Analysis", "Insight", "Solution 
                         Analysis",
                        "Session Ending Strategies"),
               l=40) +                    # Use darker colors, lightness=40
ggtitle("Mean Therapist Adherencefect over Session") +
expand_limits(y=0) +                        # Expand y range
scale_y_continuous(breaks=0:20*.5) +         # Set tick every .5
theme_bw() +
theme(legend.justification=c(1,0),
    legend.position=c(1,0))               # Position legend in bottom right

`

标签: rggplot2graph

解决方案


我认为您可能需要重新表述这个问题。您需要将数据框从宽格式转换为长格式,即。而不是单独的列 Q1-Q12,制作一个具有 Q1-Q12 标签和单独值列的单个(因子)列。然后你可以在ggplot中按颜色分割线条,例如。

ggplot(meant41, aes(x=Group.2, y=ValueColumn, color=Q)) + 
geom_line()

要获得长格式,请查看 tidyr:gather,类似于:

new_df <- gather(meant41,Q,ValueColumn,Q1:Q12,factor_key=TRUE)

祝你好运。参考: http: //www.cookbook-r.com/Manipulating_data/Converting_data_between_wide_and_long_format/


推荐阅读