首页 > 解决方案 > ggplot中的多条线图,具有不同颜色的点和线和点的图例

问题描述

我有以下数据集

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")

在此处输入图像描述 如您所见,我有六个不同的案例。我的问题是,我怎样才能为点(案例)设置不同的颜色并且还有另一个图例?

先感谢您

标签: rggplot2linelegend

解决方案


例如,您可以通过使用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_lineand geom_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")

它回答了你的问题吗?


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


推荐阅读