我有一个像这样的折线图: graph http://i60.tinypic.com/iclrfn.png
df <- data.frame(x = c(1,1,2,2,1,1,2,2),
y = c(1.5,1.9,2.1,1.6,1.4,1.8,2.0,1.7),
error = c(0.2),
group = c("g1","g2","g1","g2","g3","g4","g3","g4"))
ggplot(df, aes(x = x, y = y, color = group, linetype = group)) +
geom_point() + geom_line() +
geom_errorbar(aes(ymin = y - error, ymax = y + error),
linetype = 1, width = 0.5,
position = position_dodge(width = 0.2)) +
scale_color_manual(values = c("g1"="Black", "g2"="Grey", "g3"="Black", "g4"="Grey")) +
scale_linetype_manual(values=c("g1"=1,"g2"=1,"g3"=2,"g4"=2))
我需要将其设为黑色和白色,因此对于多个群组,我同时使用了color
和linetype
。当我改变线型时,我希望误差条是实线的,尽管线条是虚线的,所以我覆盖了错误条的线型。出于某种原因,这也会改变图例,因此不再清楚哪条线是哪条线。
我知道这在某种程度上取决于color = group
中的aes
,因为当我只有线型时,传说很好。出于某种原因,我无法找到同时处理线型,颜色和实体错误栏的方法。有谁知道这是为什么?
答案 0 :(得分:2)
试试这个:
ggplot(df, aes(x = x, y = y, colour = group, group = group)) +
geom_line(aes(y=y,linetype = group)) +
geom_point()+
geom_errorbar(aes(ymin = y - error, ymax = y + error),
colour = rep(c("black","grey"),4),
width = 0.1,
position = "dodge") +
scale_color_manual(values = c("g1"="Black", "g2"="Grey", "g3"="Black", "g4"="Grey")) +
scale_linetype_manual(values=c("g1"=1,"g2"=1,"g3"=2,"g4"=2))
你不需要ggplot中的linetype = group,因为错误栏永远不会使用这个信息。你只是让它变得更复杂。 linetype将仅由线条和图例使用。错误栏需要知道颜色和分组变量,这就是为什么要将它们包含在ggplot中。
通过创建列来设置颜色:
df <- data.frame(x = c(1,1,2,2,1,1,2,2),
y = c(1.5,1.9,2.1,1.6,1.4,1.8,2.0,1.7),
error = c(0.2),
group = c("g1","g2","g1","g2","g3","g4","g3","g4"))
df$group_cols = "black"
df$group_cols[df$group %in% c("g2","g4")] = "grey"
ggplot(df, aes(x = x, y = y, colour = group, group = group)) +
geom_line(aes(y=y,linetype = group)) +
geom_point()+
geom_errorbar(aes(ymin = y - error, ymax = y + error),
colour = df$group_cols,
width = 0.1,
position = "dodge") +
scale_color_manual(values = c("g1"="Black", "g2"="Grey", "g3"="Black", "g4"="Grey")) +
scale_linetype_manual(values=c("g1"=1,"g2"=1,"g3"=2,"g4"=2))