我想把y和y画在同一个图上。
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = "l", col = "red")
plot(x, y2, type = "l", col = "green")
但当我这样画的时候,它们就不在同一个图上了。
在Matlab中是可以的,但有人知道在R中怎么做吗?
我想把y和y画在同一个图上。
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot(x, y1, type = "l", col = "red")
plot(x, y2, type = "l", col = "green")
但当我这样画的时候,它们就不在同一个图上了。
在Matlab中是可以的,但有人知道在R中怎么做吗?
当前回答
使用plotly(用主要和次要y轴从plotly中添加溶液-它似乎缺失了):
library(plotly)
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
df=cbind.data.frame(x,y1,y2)
plot_ly(df) %>%
add_trace(x=~x,y=~y1,name = 'Line 1',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE) %>%
add_trace(x=~x,y=~y2,name = 'Line 2',type = 'scatter',mode = 'lines+markers',connectgaps = TRUE,yaxis = "y2") %>%
layout(title = 'Title',
xaxis = list(title = "X-axis title"),
yaxis2 = list(side = 'right', overlaying = "y", title = 'secondary y axis', showgrid = FALSE, zeroline = FALSE))
工作演示截图:
其他回答
您可以使用plotly包中的ggplotly()函数将这里的任何gggplot2示例转换为交互式图形,但我认为这种类型的图形没有ggplot2会更好:
# call Plotly and enter username and key
library(plotly)
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
plot_ly(x = x) %>%
add_lines(y = y1, color = I("red"), name = "Red") %>%
add_lines(y = y2, color = I("green"), name = "Green")
正如@redmode所描述的,您可以使用ggplot在同一个图形设备中绘制这两条线。在这个回答中,数据是“宽”格式的。但是,在使用ggplot时,以“长”格式将数据保存在数据帧中通常是最方便的。然后,通过在美学参数中使用不同的“分组变量”,线的属性,如线类型或颜色,将根据分组变量而变化,并将出现相应的图例。
在这种情况下,我们可以使用颜色美学,它将线条的颜色匹配到数据集中变量的不同级别(这里:y1 vs y2)。但首先,我们需要将数据从宽格式融化为长格式,例如使用函数'melt'从重塑2包。这里描述了重塑数据的其他方法:将data.frame从宽格式重塑为长格式。
library(ggplot2)
library(reshape2)
# original data in a 'wide' format
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
df <- data.frame(x, y1, y2)
# melt the data to a long format
df2 <- melt(data = df, id.vars = "x")
# plot, using the aesthetics argument 'colour'
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line()
在构建多层图时,应该考虑ggplot包。这个想法是创建一个具有基本美学的图形对象,并逐步增强它。
Ggplot样式要求数据打包在data.frame中。
# Data generation
x <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x,1,1)
df <- data.frame(x,y1,y2)
基本的解决方案:
require(ggplot2)
ggplot(df, aes(x)) + # basic graphical object
geom_line(aes(y=y1), colour="red") + # first layer
geom_line(aes(y=y2), colour="green") # second layer
这里的+运算符用于向基本对象添加额外的层。
使用ggplot,您可以在绘图的每个阶段访问图形对象。比如,通常的一步一步设置是这样的:
g <- ggplot(df, aes(x))
g <- g + geom_line(aes(y=y1), colour="red")
g <- g + geom_line(aes(y=y2), colour="green")
g
G生成图形,你可以在每个阶段看到它(至少在创建一个图层之后)。情节的进一步魅力也与创造的对象。例如,我们可以为坐标轴添加标签:
g <- g + ylab("Y") + xlab("X")
g
最后的g看起来像:
更新(2013-11-08):
正如评论中所指出的,ggplot的理念建议使用长格式的数据。 您可以参考这个答案以查看相应的代码。
我认为你想要的答案是:
plot(first thing to plot)
plot(second thing to plot,add=TRUE)
也就是说,你可以在overplot中使用点。
plot(x1, y1,col='red')
points(x2,y2,col='blue')