在ggplot中按组颜色和更改线型

use*_*015 5 r ggplot2

到目前为止,我有一个数据框:

  N Method1-Simulation Method1-Analytical Method2-Simulation Method3-Analytical
1 2              0.094          0.1831891              0.158          0.2789826
2 3              0.236          0.2856285              0.434          0.4670031
3 4              0.349          0.3740548              0.568          0.6097311
4 5              0.450          0.4525999              0.682          0.7174169
5 6              0.506          0.5228121              0.781          0.7976934
6 7              0.585          0.5854665              0.851          0.8566850
Run Code Online (Sandbox Code Playgroud)

它将容纳更多的方法。我想制作一个ggplot,其中每种方法都有其自己的颜色,分析方法为实线,而模拟方法为虚线。

除了虚线,我拥有所有东西,如下所示:

longPowerCurve <- melt(powerCurve, id = "N")
colnames(longPowerCurve)[2] <- "Method"

ggplot(data=longPowerCurve,aes(x=N, y=value, colour=Method)) + geom_line() +ylab("Power") +ggtitle("Power levels for various N and distributions")+
  theme(legend.text = element_text(size = 12))
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使它自动化,以便如果我有5、6、7、8等方法,那么它们仍然可以工作?

cde*_*man 6

您可能想要拆分method.type列。这样,您可以将两个因子分别用于绘图。要使用虚线,可以使用linetype参数。

groups <- data.frame(do.call('rbind', strsplit(as.character(longPowerCurve$Method),'.',fixed=TRUE)))
colnames(groups) <- c("Method", "Type")
longPowerCurve$Method <- groups$Method
longPowerCurve$Type <- groups$Type

ggplot(data=longPowerCurve,aes(x=N, y=value, colour=Method, linetype=Type)) + 
  geom_line() +
  ylab("Power") +
  ggtitle("Power levels for various N and distributions")+
  theme(legend.text = element_text(size = 12))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • @user1357015,您提供的数据仅对方法3进行了分析,对方法2进行了模拟,因此只有纯蓝色和点绿色。如果数据包含它们,就会有这些行。 (2认同)