绘制多个列的图

时间:2017-10-21 17:40:29

标签: r ggplot2

在R编程中我想从数据集中绘制多个列的图。

例如 这是我的示例代码 在这里,我添加了更多数据集,我希望将所有值组合在一个图表中。我怎么能把它结合起来呢?

stock_apple<-read.csv(file="apple.csv",header = TRUE,sep=",")
stock_microsoft<-read.csv(file="microsoft.csv",header=TRUE,sep=",")
stock_google<-read.csv(file="google.csv",header = TRUE,sep=",")
stock_twitter<-read.csv(file="twitter.csv",header = TRUE,sep=",")

var1<-stock_apple$high
var2<-stock_google$high
var3<-stock_microsoft$high
var4<-stock_twitter$high

install.packages("ggplot2")
library(ggplot2)

#this is for only one column but i want a plot for more than one column 
qplot(var1,
      geom="histogram",
      binwidth = 0.5,  
      main = "Histogram for Apple stock_price", 
      xlab = "stock price",  
      fill=I("blue"), 
      col=I("red"), 
      alpha=I(.2),
      xlim=c(100,3000))

1 个答案:

答案 0 :(得分:1)

以下是多个列的绘图示例。希望它可以帮到你。

k <- 1000
set.seed(1)
dts1 <- data.frame(x=rnorm(k,1000,100), y=rnorm(k,1800,100),z=rnorm(k,2600,100))
dts2 <- reshape::melt(dts1)

library(ggplot2)
ggplot(data=dts2, aes(x=value,fill=variable)) +
geom_histogram(color="white", alpha=.7, binwidth = 50) +
labs(x="Stock price",title="Histogram for Apple stock_price")+
xlim(c(100,3000))

enter image description here

使用qplot

qplot(x=value, fill=variable, data=dts2,
      geom="histogram",
      binwidth = 50,  
      main = "Histogram for Apple stock_price", 
      xlab = "Stock price",  
      alpha=I(.7),
      colour=I("white"),
      xlim=c(100,3000))
相关问题