我有一些按以下三类排序的数据:
toy
# A tibble: 20 x 5
# Groups: v190, treatedgroup [10]
Size Animal Fluffy AvgWeight SE
<fct> <fct> <fct> <dbl> <dbl>
1 Tiny Dog Shorthair 114. 0.0724
2 Tiny Dog Longhair 113. 0.0904
3 Tiny Cat Shorthair 117. 0.150
4 Tiny Cat Longhair 114. 0.318
5 Small Dog Shorthair 116. 0.0685
6 Small Dog Longhair 115. 0.0974
7 Small Cat Shorthair 119. 0.119
8 Small Cat Longhair 116. 0.316
9 Medium Dog Shorthair 116. 0.0662
10 Medium Dog Longhair 117. 0.106
11 Medium Cat Shorthair 120. 0.118
12 Medium Cat Longhair 117. 0.294
13 Large Dog Shorthair 117. 0.0662
14 Large Dog Longhair 118. 0.111
15 Large Cat Shorthair 120. 0.114
16 Large Cat Longhair 118. 0.267
17 Giant Dog Shorthair 118. 0.0633
18 Giant Dog Longhair 120. 0.103
19 Giant Cat Shorthair 121. 0.123
20 Giant Cat Longhair 120. 0.265
我想将此绘制为带有置信区间的折线图。我希望颜色能反映动物,而线型则能反映Fluffy。下面的图正是我想要的图,但图例未合并。代表线型的黑线令人困惑。我遵循建议here尝试对其进行修复,但是如您所见,它不起作用。
ggplot(data = toy, aes(x = Size, y = AvgWeight, color=Animal,
linetype=Fluffy)) +
geom_line(aes(x = Size, y = AvgWeight,
group=interaction(Animal,Fluffy)), size=1) +
geom_point() +
geom_errorbar(aes(ymax = AvgWeight + SE,
ymin = AvgWeight - SE), width = 0.05, size=1) +
scale_color_discrete("Key") +
scale_linetype_manual(name="Key",values= rep(1:2,2))
然后我尝试创建交互,如下所示:
ggplot(data = toy, aes(x = Size, y = AvgWeight, color=interaction(Animal,Fluffy),
linetype=interaction(Animal,Fluffy))) +
geom_line(aes(x = Size, y = AvgWeight,
group=interaction(Animal,Fluffy)), size=1) +
geom_point() +
geom_errorbar(aes(ymax = AvgWeight + SE,
ymin = AvgWeight - SE), width = 0.05, size=1) +
scale_color_discrete("Key") +
scale_linetype_manual(name="Key",values= rep(1:2,2))
这段代码给了我一个看起来正确的图例,但现在的颜色一团糟:
在scale_color_discrete中指定颜色会给我以下错误:
Error in discrete_scale(aesthetics, "hue", hue_pal(h, c, l, h.start, direction), :
unused argument (values = c(Dog.Shorthair = "indianred4", Cat.Shorthair = "dodgerblue4", Dog.Longhair = "indianred4", Cat.Longhair = "dodgerblue4"))
我在做什么错?如何在第二张图中手动指定颜色,或在第一张图中合并图例?
答案 0 :(得分:1)
我只能从上面读取它的表格,因此我没有您所需要的水平。因此,以下内容应或多或少起作用,您只需要在数据框上以正确的级别进行尝试,并在需要时翻转颜色/线型:
toy$int = with(toy,interaction(Animal,Fluffy))
ggplot(data = toy, aes(x = Size, y = AvgWeight,color=int,
linetype=int)) +
geom_line(aes(group=int)) +
geom_point() +
geom_errorbar(aes(ymax = AvgWeight + SE,
ymin = AvgWeight - SE), width = 0.05, size=1)+
scale_color_manual(values=rep(c("dodgerblue4","indianred4"),2)) +
scale_linetype_manual(values=rep(c("solid","dashed"),each=2))