【问题标题】:ggplot line graph with different line styles and markers具有不同线型和标记的ggplot折线图
【发布时间】:2014-12-08 10:13:03
【问题描述】:

我正在尝试在 ggplot2 中创建一个折线图,它结合了某些变量的不同线条样式和其他变量的不同标记。

示例 1 使用不同的线型绘制每个变量,示例 2 使用不同的标记绘制每个变量,示例 3 使用不同的线和标记绘制每个变量。

我试图用不同的线条样式(实线、虚线)绘制 X2 和 X3,然后将 X4 和 X5 绘制为具有不同标记(圆形、正方形等)的实线。

有什么办法吗?

library(ggplot2)
library(reshape2)

set.seed <- 1
df <- data.frame(cbind(seq(1,10,1),matrix(rnorm(100,1,20), 10, 4)))
d <- melt(df, id="X1")

# Example 1: different line styles
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line(aes(linetype=variable), size=1)

# Example 2: different markers for each line
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line() + geom_point(aes(shape=variable, size=4))

# Example 3: differnt line styles & different markers (You see this graph below)
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line(aes(linetype=variable), size=1) +
  geom_point(aes(shape=variable, size=4))

【问题讨论】:

  • 作为第一个问题,这是用可重现的样本写得很好。干得好!:)

标签: r ggplot2


【解决方案1】:

这是一种方法。您可以使用另外两个函数来控制形状和线型。 scale_linetype_manual 允许您手动分配线型。同样,scale_shape_manual 允许您手动分配您想要的任何形状。

# Example 3: differnt line styles & different markers
ggplot(d, aes(x=X1, y=value, color=variable)) + 
geom_line(aes(linetype=variable), size=1) +
geom_point(aes(shape=variable, size=4)) +
scale_linetype_manual(values = c(1,2,1,1)) +
scale_shape_manual(values=c(0,1,2,3))

【讨论】:

  • 太棒了!非常感谢你的帮助。我显然还在学习 ggplot2 的所有功能。
  • @learnmorer 很高兴。 :) 我还在每天学习 ggplot2!
  • 我认为 geom_point 行有错误。大小应在括号外:geom_point(aes(shape=variable), size=4)
  • @luchonacho 提供的更正也去掉了图例中的黑点“4”。
猜你喜欢
  • 1970-01-01
  • 2021-03-04
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 2015-10-14
  • 2021-09-23
  • 2022-01-12
相关资源
最近更新 更多