ggplot中的多个线图,具有不同颜色的点和图例,用于线和点

时间:2020-03-10 20:06:12

标签: r ggplot2 line legend

我有以下数据集

data = data.frame(tmu = c(0.1164966,0.01649658, 0.605479878,0.073743729, 0.21649659,0.543409994,0.1164966,0.01649658,0.605479878,
                  0.073743729,0.21649659,0.543409994,0.1164966,0.01649658,0.605479878, 0.073743729, 0.21649659,0.543409994)
                  , Method = c( rep('M1', 6), rep('M2', 6), rep('M3', 6)),
                  Value = c(1.140242, 1.016913, 2.211742,1.07824, 1.312171, 1.872045,1.131858,1.016773, 1.982265,1.077372, 1.276319,
                            1.771913,1.131858, 1.016773,1.932845, 1.077338,  1.276319, 1.756129),
                  cases = rep(c('A', 'B', 'C', 'D', 'E', 'F'),3))

我使用以下代码生成了下图。

pd <- position_dodge(width = 0.4)

ggplot(data, aes(x=tmu, y=Value, color=Method)) + 
  geom_line(size = .3, position = pd) +
  geom_point(size = 2, shape = 18, position = pd) +
  labs(fill = "") +
  theme(legend.position="bottom")

enter image description here 如您所见,我有六个不同的案例。我的问题是,我该如何为点(例)设置不同的颜色,并且还要有另一个图例?

提前谢谢

1 个答案:

答案 0 :(得分:4)

例如,可以使用fillcolor参数来区分点和线。在选择允许填充的点的形状(例如shape = 21)时,线的颜色和点的填充:

ggplot(data, aes(x=tmu, y=Value, color = Method, group = Method)) + 
  geom_line(size = .3, position = pd) +
  geom_point(aes(fill = cases),color = "black", shape = 21,size = 2, position = pd) +
  labs(fill = "") +
  theme(legend.position="bottom")

或者您可以将不同的color参数传递到geom_linegeom_point中:

ggplot(data, aes(x=tmu, y=Value, group = Method)) + 
  geom_line(aes(color = Method), size = .3, position = pd) +
  geom_point(aes(color = cases),size = 2, shape = 18, position = pd) +
  labs(fill = "") +
  theme(legend.position="bottom")

它回答了您的问题吗?


注意:由于某些原因,我无法上传输出图的图像...对此感到抱歉

相关问题